"""``mgf-fed conformance`` — the authoritative fleet conformance audit.

Thin wrapper over mgf-standard's ``scripts/fleet_conformance_audit.py`` (the canonical
scorer) — the same relationship ``mgf-fed registry`` has to ``gen_mgf_libraries.py``.

Why this exists as a verb: ``mgf-fed status`` dropped its ``conf%`` column under CIR-15
(the percentage scored repos against rules they never declared) and its footer pointed
readers at a **file path**. A path is not a tool — it cannot be listed, installed, or
discovered, so the authoritative measure was the least reachable thing in the fleet.
This makes the pointer runnable.

The audit runs ``mgf-fed catch-up`` read-only across every on-disk ``mgf-*`` repo, so it
takes minutes and streams its progress rather than buffering. It never mutates a target
repo; it does write its tracker to ``mgf-standard/docs/inprogress/FLEET_AUDIT/``.
"""

from __future__ import annotations

import os
import shutil
import subprocess
import sys
from pathlib import Path

from mgf.fed._roster import federation_root

# The audit shells `mgf-fed catch-up` per repo across the whole fleet; minutes, not
# seconds. Bounded anyway — a wrapper that can hang forever is its own outage.
_TIMEOUT_S = 3600


def run_conformance(
    *,
    json_only: bool = False,
    generated: str | None = None,
    extra_roots: tuple[str, ...] = (),
    root: Path | None = None,
) -> int:
    root = root or federation_root()
    standard = root / "mgf-standard"
    audit = standard / "scripts" / "fleet_conformance_audit.py"
    if not audit.is_file():
        print(f"conformance auditor not found at {audit} — is mgf-standard cloned under the root?")
        return 2

    # The script stamps the tracker "UNSTAMPED (pass --generated)" when neither the flag
    # nor AUDIT_TS is set. Say so up front rather than let it be discovered in the output.
    if generated is None and not os.environ.get("AUDIT_TS"):
        print(
            "note: no --generated and no AUDIT_TS — the tracker will be written UNSTAMPED. "
            "Pass --generated YYYY-MM-DD for a dated, reproducible run."
        )

    python = shutil.which("python3") or sys.executable
    args = [python, str(audit)]
    if json_only:
        args.append("--json-only")
    if generated is not None:
        args += ["--generated", generated]
    for extra in extra_roots:
        args += ["--root", extra]

    # Streamed, not captured: this runs for minutes across the fleet, and a wrapper that
    # swallows progress until the end reads as a hang.
    try:
        p = subprocess.run(args, cwd=str(standard), timeout=_TIMEOUT_S)  # noqa: S603
    except subprocess.TimeoutExpired:
        print(f"conformance audit exceeded {_TIMEOUT_S}s — aborted (no tracker written)")
        return 2
    except (OSError, subprocess.SubprocessError) as exc:
        print(f"conformance run failed: {exc}")
        return 2
    return p.returncode
