"""``mgf-fed version`` — rich version + build/runtime provenance (OP-01).

One command answers "exactly what am I running?" — the package version, the
git commit it was built from (when discoverable), the Python + platform it
runs on, and the versions of the load-bearing runtime dependencies. The
console script also answers the bare ``mgf-common --version`` flag (which the
release smoke-test invokes — WF-07), intercepted in ``_mgfcli.main`` before
argparse.

Best-effort + side-effect-free: the git SHA is read via a short, list-argv
``git`` call (SC-02) only when a ``.git`` is present (editable/dev installs);
a PyPI-installed wheel simply omits it. Every lookup is exception-guarded so
``version`` can never crash the host.
"""

from __future__ import annotations

import json
import platform
from typing import TYPE_CHECKING

from mgf.common.cli import EXIT_SUCCESS

if TYPE_CHECKING:
    import argparse

# The runtime deps whose versions are worth surfacing (the ones that ship
# transitively into every consumer — see pyproject `dependencies`).
_KEY_DEPS = ("pydantic", "pydantic-settings", "pyyaml")


def _git_sha() -> str | None:
    """Short HEAD SHA when run from a checkout, else None (installed wheel)."""
    import contextlib

    with contextlib.suppress(Exception):
        import subprocess
        from pathlib import Path

        # src/mgf/common/cli/_version.py → repo root is parents[4].
        root = Path(__file__).resolve().parents[4]
        if (root / ".git").exists():
            out = subprocess.run(
                ["git", "-C", str(root), "rev-parse", "--short", "HEAD"],  # noqa: S607
                capture_output=True,
                text=True,
                timeout=2,
                check=False,
            )
            if out.returncode == 0 and out.stdout.strip():
                return out.stdout.strip()
    return None


def _dep_version(name: str) -> str:
    try:
        from importlib.metadata import version

        return version(name)
    except Exception:
        return "?"


def version_facts() -> dict[str, object]:
    """The machine-readable version payload (also the `--json` shape)."""
    from mgf.common import __version__

    return {
        "name": "mgf-common",
        "version": __version__,
        "commit": _git_sha(),
        "python": platform.python_version(),
        "python_impl": platform.python_implementation(),
        "platform": f"{platform.system()} {platform.machine()}",
        "deps": {dep: _dep_version(dep) for dep in _KEY_DEPS},
    }


def render_version() -> str:
    """Human-readable multi-line version block (OP-01 shape)."""
    f = version_facts()
    lines = [f"mgf-common {f['version']}"]
    if f["commit"]:
        lines.append(f"  commit:   {f['commit']}")
    lines.append(f"  python:   {f['python']} ({f['python_impl']})")
    lines.append(f"  platform: {f['platform']}")
    deps = f["deps"]
    assert isinstance(deps, dict)
    lines.append("  deps:     " + ", ".join(f"{k} {v}" for k, v in deps.items()))
    return "\n".join(lines)


def add_version_args(parser: argparse.ArgumentParser) -> None:
    parser.add_argument(
        "--json",
        action="store_true",
        help="Emit the version facts as a single JSON object.",
    )


def run_version(args: argparse.Namespace) -> int:
    if getattr(args, "json", False):
        print(json.dumps(version_facts(), separators=(",", ":")))
    else:
        print(render_version())
    return EXIT_SUCCESS
