"""``mgf-fed registry`` — regenerate (and ``--check``) the federation registry.

Thin wrapper over mgf-standard's ``scripts/gen_mgf_libraries.py`` (the canonical generator):
``mgf-fed registry`` regenerates ``MGF_LIBRARIES.{md,json}``; ``--check`` runs the REL-13
consistency + currency gate (exit 1 on an inconsistent pin or a stale committed registry).

**What the gate READS is chosen here** (PAPER-152). The generator walks a federation
root and reads each sibling's files; mgf-fed owns which root it walks. ``--check``
walks an ``origin/<default>`` mirror (``_origin_view``), so the verdict describes the
fleet that exists on the remotes. A plain regen still walks the working trees,
because writing the registry from anything else would render an artifact the
operator cannot reproduce from what they can see — but it says so loudly.
"""

from __future__ import annotations

import shutil
import subprocess
import sys
import tempfile
from pathlib import Path

from mgf.fed import _origin_view
from mgf.fed._roster import federation_root, print_divergence_banner

#: What the gate resolves members against. ``origin`` is the default for ``--check``:
#: it is the only source that can answer "is the FLEET consistent". ``worktree`` is
#: the deliberate local preview — PAPER-152's third offer, kept one flag away so the
#: safe path is the default rather than the informed choice.
SOURCES = ("origin", "worktree")


def _run_generator(gen: Path, cwd: Path, *, check: bool) -> tuple[int, str]:
    python = shutil.which("python3") or sys.executable
    args = [python, str(gen), *(["--check"] if check else [])]
    try:
        p = subprocess.run(  # noqa: S603 — fixed argv, no shell
            args, cwd=str(cwd), capture_output=True, text=True, timeout=180
        )
    except (OSError, subprocess.SubprocessError) as exc:
        return 2, f"registry run failed: {exc}"
    return p.returncode, (p.stdout + p.stderr).strip()


def run_registry(
    *, check: bool = False, root: Path | None = None, source: str | None = None, fetch: bool = False
) -> int:
    root = root or federation_root()
    standard = root / "mgf-standard"
    gen = standard / "scripts" / "gen_mgf_libraries.py"
    if not gen.is_file():
        print(f"registry generator not found at {gen} — is mgf-standard cloned under the root?")
        return 2

    # `--check` defaults to origin: a consistency verdict about the fleet must be
    # measured against the fleet. A regen defaults to the worktree: it WRITES a file
    # the operator has to be able to reproduce.
    source = source or ("origin" if check else "worktree")
    if source not in SOURCES:
        print(f"registry: unknown --source={source!r} (want one of {', '.join(SOURCES)})")
        return 2

    # The divergence banner (PAPER-152's first offer, 0.25.0) goes to STDERR — see
    # `_roster.print_divergence_banner`. It is informational context about the
    # bench, never a finding, and the difference is a stream.
    print_divergence_banner(
        sorted(p for p in root.iterdir() if p.is_dir()),
        subject="The registry generator" if not check else "The registry consistency gate",
    )

    if source == "worktree":
        if check:
            # An explicitly-requested local preview. Say plainly that the verdict is
            # not about any remote, so a red from it is never mistaken for a fleet red.
            print(
                "registry --check --source=worktree: grading the BENCH's working trees. "
                "This verdict does not describe any remote (PAPER-152).",
                file=sys.stderr,
            )
        rc, out = _run_generator(gen, standard, check=check)
        if out:
            print(out)
        return rc

    # origin: materialise a mirror of every member at its origin default branch and
    # point the (unmodified) generator at that instead of at the bench.
    with tempfile.TemporaryDirectory(prefix="mgf-fed-origin-view-") as tmp:
        view = _origin_view.materialize(root, Path(tmp), fetch=fetch)
        banner = view.degradation_banner()
        if banner:
            print(banner, file=sys.stderr, flush=True)
        mirror_gen = view.root / "mgf-standard" / "scripts" / "gen_mgf_libraries.py"
        if not mirror_gen.is_file():
            print(
                "registry: could not materialise mgf-standard at its origin default "
                f"({view.root / 'mgf-standard'} has no generator) — refusing to grade a "
                "partial fleet. Re-run with --source=worktree to preview locally.",
                file=sys.stderr,
            )
            return 2
        rc, out = _run_generator(mirror_gen, view.root / "mgf-standard", check=check)
    if out:
        print(out)
    return rc
