"""``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).
"""

from __future__ import annotations

import shutil
import subprocess
import sys
from pathlib import Path

from mgf.fed._roster import federation_root


def run_registry(*, check: bool = False, root: Path | None = None) -> 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
    python = shutil.which("python3") or sys.executable
    args = [python, str(gen), *(["--check"] if check else [])]
    try:
        p = subprocess.run(args, cwd=str(standard), capture_output=True, text=True, timeout=180)  # noqa: S603
    except (OSError, subprocess.SubprocessError) as exc:
        print(f"registry run failed: {exc}")
        return 2
    out = (p.stdout + p.stderr).strip()
    if out:
        print(out)
    return p.returncode
