"""Read a git repo's current commit sha WITHOUT the git binary (read-only).

The console is read-mostly and testctl runs as an isolated tool; neither should
shell out to git. This resolves ``<root>/.git/HEAD`` — a symbolic ref
(``ref: refs/heads/main``) followed one hop into ``refs/`` or ``packed-refs``, or
a detached bare sha. Returns ``None`` on anything it can't resolve (a worktree
``.git`` file, no repo, an unborn branch) — the caller then simply shows nothing,
never a wrong answer.
"""

from __future__ import annotations

from pathlib import Path


def head_commit(root: str | Path) -> str | None:
    """The commit ``<root>`` currently points at, or ``None`` if unresolvable."""
    git = Path(root) / ".git"
    if not git.is_dir():  # worktree/submodule .git *file*, or no repo — don't guess
        return None
    try:
        head = (git / "HEAD").read_text(encoding="utf-8").strip()
    except (OSError, UnicodeDecodeError):
        return None
    if not head.startswith("ref:"):
        return head or None  # detached HEAD: a bare sha
    ref = head[4:].strip()  # e.g. "refs/heads/main"
    loose = git / ref
    if loose.is_file():
        try:
            return loose.read_text(encoding="utf-8").strip() or None
        except OSError:
            return None
    packed = git / "packed-refs"
    if packed.is_file():
        try:
            for raw in packed.read_text(encoding="utf-8").splitlines():
                line = raw.strip()
                if line and not line.startswith(("#", "^")) and line.endswith(" " + ref):
                    return line.split(" ", 1)[0]
        except OSError:
            return None
    return None
