"""``mgf-cloud 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 (incl. the optional
provider SDKs, when installed). This is the first-triage line for a bug report,
so the version source is the single-sourced :data:`mgf.cloud.__version__`
(metadata, AP-13) — never a stale literal.

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
wheel install 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.cloud import __version__

if TYPE_CHECKING:
    import argparse

# The runtime deps worth surfacing: the always-present core, then the optional
# provider/transport SDKs (reported as "(not installed)" when the matching extra
# is absent — itself a useful triage signal).
_KEY_DEPS = (
    "mgf-common",
    "pydantic",
    "pydantic-settings",
    "pyyaml",
    "openstacksdk",
    "paramiko",
    "boto3",
)


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/cloud/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 "(not installed)"


def version_facts() -> dict[str, object]:
    """The machine-readable version payload (also the ``--json`` shape)."""
    return {
        "name": "mgf-cloud",
        "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-cloud {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:")
    for name, ver in deps.items():
        lines.append(f"    {name:18} {ver}")
    return "\n".join(lines)


def run_version(args: argparse.Namespace) -> int:
    """Argparse-callback wiring for the ``version`` subcommand."""
    if getattr(args, "as_json", False):
        print(json.dumps(version_facts(), indent=2, sort_keys=True))
    else:
        print(render_version())
    return 0


__all__ = ["render_version", "run_version", "version_facts"]
