"""Tests for the registry wrapper."""

from __future__ import annotations

from pathlib import Path

import pytest

from mgf.fed import _registry
from mgf.fed._registry import run_registry


class _FakeProc:
    def __init__(self, returncode: int, out: str) -> None:
        self.returncode = returncode
        self.stdout = out
        self.stderr = ""


def _with_gen(tmp_path: Path) -> Path:
    gen = tmp_path / "mgf-standard" / "scripts" / "gen_mgf_libraries.py"
    gen.parent.mkdir(parents=True)
    gen.write_text("# generator", encoding="utf-8")
    return tmp_path


def test_registry_generator_missing(tmp_path: Path) -> None:
    assert run_registry(root=tmp_path) == 2  # no mgf-standard/scripts/gen_mgf_libraries.py


# These two pin the WRAPPER's contract — it propagates the generator's exit code and
# prints its output — over a bare stub root that is not a git clone. Since 0.25.1
# `--check` resolves members at origin/<default> (PAPER-152's resolution half), and a
# root with no clones has no origin to resolve, so they name `source="worktree"`
# explicitly. That is not a weakening: WHICH tree the gate grades is now a contract of
# its own, pinned in tests/unit/test_origin_view.py, and this file stops conflating
# the two questions.


def test_registry_check_green(
    tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
) -> None:
    monkeypatch.setattr(
        _registry.subprocess, "run", lambda *a, **k: _FakeProc(0, "REGISTRY CURRENCY: CURRENT")
    )
    assert run_registry(check=True, root=_with_gen(tmp_path), source="worktree") == 0
    assert "CURRENT" in capsys.readouterr().out


def test_registry_check_failure_propagates(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.setattr(_registry.subprocess, "run", lambda *a, **k: _FakeProc(1, "STALE"))
    assert run_registry(check=True, root=_with_gen(tmp_path), source="worktree") == 1


def test_registry_check_REFUSES_to_grade_when_mgf_standard_cannot_be_resolved(
    tmp_path: Path, capsys: pytest.CaptureFixture[str]
) -> None:
    """New in 0.25.1, and a strengthening rather than a side effect.

    If mgf-standard itself cannot be read at its origin default, the registry being
    graded is unknown — so the gate returns 2, which `_audit` maps to SKIPPED. "I
    could not grade the fleet" must never share an outcome with "the fleet is
    consistent"; that is the principle `check_registry_consistency` already applies
    to the generator's own exit 2, extended to the tree it reads.
    """
    assert run_registry(check=True, root=_with_gen(tmp_path)) == 2
    assert "refusing to grade a partial fleet" in capsys.readouterr().err
