"""``_gitref.head_commit`` — read a repo's commit without the git binary."""

from __future__ import annotations

from pathlib import Path

from mgf.test_web._gitref import head_commit


def test_head_commit_loose_ref(tmp_path: Path) -> None:
    git = tmp_path / ".git"
    (git / "refs" / "heads").mkdir(parents=True)
    (git / "HEAD").write_text("ref: refs/heads/main\n", encoding="utf-8")
    (git / "refs" / "heads" / "main").write_text("abc123def456\n", encoding="utf-8")
    assert head_commit(tmp_path) == "abc123def456"


def test_head_commit_detached(tmp_path: Path) -> None:
    git = tmp_path / ".git"
    git.mkdir()
    (git / "HEAD").write_text("deadbeefcafe0000\n", encoding="utf-8")
    assert head_commit(tmp_path) == "deadbeefcafe0000"


def test_head_commit_packed_refs(tmp_path: Path) -> None:
    git = tmp_path / ".git"
    git.mkdir()
    (git / "HEAD").write_text("ref: refs/heads/main\n", encoding="utf-8")
    (git / "packed-refs").write_text(
        "# pack-refs with: peeled fully-peeled sorted\nabc123 refs/heads/main\n^peeledtag\n",
        encoding="utf-8",
    )
    assert head_commit(tmp_path) == "abc123"


def test_head_commit_none_without_repo(tmp_path: Path) -> None:
    assert head_commit(tmp_path) is None  # no .git dir → don't guess


def test_head_commit_none_for_git_file(tmp_path: Path) -> None:
    (tmp_path / ".git").write_text("gitdir: /elsewhere\n", encoding="utf-8")  # worktree
    assert head_commit(tmp_path) is None
