#!/usr/bin/env python3
"""Regenerate the fleet co-install roster + lock (run after a cornerstone ripple).

Reads the python ``mgf-*`` members from the mgf-standard registry
(``MGF_LIBRARIES.json``, found via ``$MGF_ROOT`` or the federation parent dir),
rewrites ``fleet-coinstall.in``, and resolves it against devpi with ``uv`` into
``fleet-coinstall.lock``. Commit both. The committed lock's ``mgf-common==`` line
is the cornerstone the whole fleet co-installs at; ``test_fleet_coinstall.py``
fails if devpi drifts from it (a leaf lagging) or if the lock goes stale.

Usage:  python tests/fleet/refresh_lock.py
"""

from __future__ import annotations

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

_HERE = Path(__file__).resolve().parent
_ROSTER = _HERE / "fleet-coinstall.in"
_LOCK = _HERE / "fleet-coinstall.lock"
_DEVPI = "https://195.15.203.250.sslip.io/magogi/prod/+simple/"

_ROSTER_HEADER = """\
# Federation co-install roster — every published python mgf-* library.
# Drives tests/fleet/test_fleet_coinstall.py, which asserts the WHOLE fleet
# co-installs at the current mgf-common cornerstone (catches the devpi
# "leaves lag the cornerstone" backfill gap before a human does).
# Regenerate this + fleet-coinstall.lock with:  python tests/fleet/refresh_lock.py
"""

_LOCK_HEADER = (
    "# Committed full-fleet uv lockfile — the resolution of "
    "tests/fleet/fleet-coinstall.in\n"
    "# against devpi. mgf-common== below is the cornerstone the whole fleet "
    "co-installs at.\n"
    "# Generated by tests/fleet/refresh_lock.py (uv pip compile --refresh). "
    "DO NOT hand-edit.\n#\n"
)


def _registry_path() -> Path:
    root = Path(os.environ["MGF_ROOT"]).expanduser() if os.environ.get("MGF_ROOT") else None
    for cand in (root, Path.home() / "PycharmProjects", Path.cwd().parent):
        if cand and (cand / "mgf-standard" / "MGF_LIBRARIES.json").is_file():
            return cand / "mgf-standard" / "MGF_LIBRARIES.json"
    sys.exit("error: mgf-standard/MGF_LIBRARIES.json not found (set MGF_ROOT)")


def main() -> int:
    uv = shutil.which("uv")
    if uv is None:
        sys.exit("error: uv not on PATH (pip install uv)")
    data = json.loads(_registry_path().read_text(encoding="utf-8"))
    libs = sorted(lib["repo"] for lib in data["libraries"] if lib.get("lang") == "python")
    _ROSTER.write_text(_ROSTER_HEADER + "\n".join(libs) + "\n", encoding="utf-8")
    print(f"wrote {_ROSTER.name} ({len(libs)} libs)")
    proc = subprocess.run(  # noqa: S603
        [uv, "pip", "compile", str(_ROSTER), "--index-url", _DEVPI,
         "--index-strategy", "unsafe-best-match", "--refresh", "--no-header", "--quiet"],
        capture_output=True, text=True, timeout=300,
    )
    if proc.returncode != 0:
        sys.exit(f"uv pip compile FAILED — fleet does not co-install:\n{proc.stderr}")
    _LOCK.write_text(_LOCK_HEADER + proc.stdout, encoding="utf-8")
    cs = next((ln.split("==")[1].strip() for ln in proc.stdout.splitlines()
               if ln.strip().startswith("mgf-common==")), "?")
    print(f"wrote {_LOCK.name} (cornerstone mgf-common=={cs})")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
