"""``mgf-fed doctor`` — self-diagnostic (OP-02): probe mgf-fed's own operational prerequisites.

A pass/fail checklist of what mgf-fed needs to function — the federation root, the registry it
reads, the scaffolding policy, the local index — plus an informational note on which composed
external tools are on PATH (each command guards its own). Distinct from `drift-check`/`status`,
which probe the *federation*; this probes mgf-fed itself.
"""

from __future__ import annotations

import shutil
from pathlib import Path

from mgf.fed import _index, _roster, _template

_COMPOSED_TOOLS = ("uv", "ruff", "git", "tea", "woodpecker-cli")


def run_doctor(*, root: Path | None = None) -> int:
    root = root or _roster.federation_root()
    registry = root / "mgf-standard" / "MGF_LIBRARIES.json"
    policy = _template.template_dir(root) / "policy.toml"

    checks: list[tuple[bool, str, str]] = [
        (
            root.is_dir(),
            f"federation root resolves ({root})",
            "set $MGF_ROOT or clone the fleet there",
        ),
        (
            registry.is_file(),
            "mgf-standard registry present (MGF_LIBRARIES.json)",
            "clone mgf-standard under the root",
        ),
        (
            policy.is_file(),
            "scaffolding policy present (templates/policy.toml)",
            "mgf-standard/templates/policy.toml missing",
        ),
        (_index.local_index_dir().is_dir(), f"local index ready ({_index.local_index_dir()})", ""),
    ]

    print("mgf-fed doctor — self-check:")
    for ok, label, hint in checks:
        print(f"  {'✓' if ok else '✗'} {label}" + ("" if ok or not hint else f"  → {hint}"))
    for tool in _COMPOSED_TOOLS:
        present = shutil.which(tool) is not None
        print(
            f"  {'✓' if present else '·'} tool {tool}"
            + ("" if present else " (not on PATH — needed by some commands)")
        )

    core_ok = all(ok for ok, _, _ in checks)
    fails = sum(1 for ok, _, _ in checks if not ok)
    print(f"\n{'OK — prerequisites met' if core_ok else f'FAIL — {fails} prerequisite(s) missing'}")
    return 0 if core_ok else 1
