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


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)) == 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)) == 1
