"""Fleet co-install gate — the whole mgf-* fleet must resolve at the cornerstone.

After an ``mgf-common`` cornerstone bump, every consumer is pin-walked to admit
the new minor, but a leaf's *published* artifact can still cap ``mgf-common``
below it (pin-walked on ``main`` but never republished — the devpi backfill
gap). When that happens a full-graph ``uv`` resolve of the fleet silently
backtracks to an *older* mgf-common where every published pin agrees, so
``uv pip install <all mgf-*>`` no longer installs the cornerstone. REL-13
(which reads pyproject ``main``) stays green and nobody notices until an install
does the wrong thing.

This test catches it: it resolves the full fleet (``fleet-coinstall.in``) from
devpi and asserts ``mgf-common`` resolves to the **same version mgf-fed itself
installed** — i.e. the cornerstone. A lagging leaf drags the fleet resolution
below that and turns this red.

Self-contained (mgf-fed cannot read the mgf-standard registry in CI): the roster
is committed, and the cornerstone is read from the installed ``mgf-common``.
Skipped unless ``uv`` is on PATH and devpi is reachable, so it runs in CI (which
installs from devpi) and skips offline/unit runs.
"""

from __future__ import annotations

import importlib.metadata as md
import shutil
import ssl
import subprocess
import urllib.request
from pathlib import Path

import pytest

pytestmark = pytest.mark.integration

_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/"


def _devpi_reachable() -> bool:
    ctx = ssl.create_default_context()
    ctx.check_hostname = False
    ctx.verify_mode = ssl.CERT_NONE
    try:
        urllib.request.urlopen(_DEVPI + "mgf-common/", context=ctx, timeout=10)  # noqa: S310
    except Exception:
        return False
    return True


def _mgf_common_pin(text: str) -> str | None:
    """The ``mgf-common`` version from a uv/pip-compile lockfile body."""
    for line in text.splitlines():
        s = line.strip()
        if s.startswith("mgf-common=="):
            return s.split("==", 1)[1].split()[0]
    return None


@pytest.fixture(scope="module")
def uv_bin() -> str:
    uv = shutil.which("uv")
    if uv is None:
        pytest.skip("uv not installed (it is in the [dev] extra / CI image)")
    if not _devpi_reachable():
        pytest.skip("devpi index unreachable (offline)")
    return uv


def _resolve_fleet(uv: str, tmp_path: Path) -> str:
    out_file = tmp_path / "resolved.txt"
    proc = subprocess.run(  # noqa: S603
        [
            uv, "pip", "compile", str(_ROSTER),
            "--index-url", _DEVPI,
            "--index-strategy", "unsafe-best-match",
            "--refresh", "--quiet",
            "-o", str(out_file),
        ],
        capture_output=True,
        text=True,
        timeout=300,
    )
    assert proc.returncode == 0, (
        "the published mgf-* fleet does NOT co-install — uv could not resolve the "
        "full graph from devpi:\n" + (proc.stderr or proc.stdout)[-2000:]
    )
    return out_file.read_text(encoding="utf-8")


# a cold `uv pip compile --refresh` over the network can exceed the 30s default
@pytest.mark.timeout(180)
def test_fleet_coinstalls_at_cornerstone(uv_bin: str, tmp_path: Path) -> None:
    cornerstone = md.version("mgf-common")  # the version mgf-fed itself resolved
    resolved = _mgf_common_pin(_resolve_fleet(uv_bin, tmp_path))
    assert resolved == cornerstone, (
        f"fleet co-install REGRESSED: resolving the whole mgf-* fleet from devpi "
        f"pins mgf-common=={resolved}, but the cornerstone (mgf-fed's own installed "
        f"mgf-common) is {cornerstone}. A leaf's PUBLISHED artifact caps mgf-common "
        f"below the cornerstone (pin-walked on main but not republished) — uv "
        f"backtracked the whole fleet to {resolved}. Backfill the lagging leaf "
        f"(patch release carrying the widened pin to devpi); see the "
        f"cornerstone-ripple-playbook. Then refresh tests/fleet/fleet-coinstall.lock."
    )


def test_committed_lock_matches_cornerstone(uv_bin: str) -> None:
    """The committed lock is stale if its mgf-common drifts from the cornerstone."""
    locked = _mgf_common_pin(_LOCK.read_text(encoding="utf-8"))
    cornerstone = md.version("mgf-common")
    assert locked == cornerstone, (
        f"tests/fleet/fleet-coinstall.lock pins mgf-common=={locked} but the "
        f"cornerstone is {cornerstone} — regenerate it: python tests/fleet/refresh_lock.py"
    )
