"""Tests for the self-diagnostic (OP-02)."""

from __future__ import annotations

import subprocess
from pathlib import Path

import pytest

from mgf.fed import _doctor
from mgf.fed._doctor import run_doctor


def _std(tmp_path: Path) -> None:
    std = tmp_path / "mgf-standard"
    (std / "templates").mkdir(parents=True)
    (std / "MGF_LIBRARIES.json").write_text("{}", encoding="utf-8")
    (std / "templates" / "policy.toml").write_text("schema = 1\n", encoding="utf-8")


def test_doctor_pass(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:
    _std(tmp_path)
    assert run_doctor(root=tmp_path) == 0
    assert "OK" in capsys.readouterr().out


def test_doctor_fail_missing_registry(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:
    assert run_doctor(root=tmp_path) == 1  # no mgf-standard registry
    assert "FAIL" in capsys.readouterr().out


# --- board item 36: is the mgf-fed running this command the one on main? -------


class TestInstalledIsCurrent:
    def test_running_from_the_checkout_cannot_lag(self, tmp_path: Path) -> None:
        """An editable install IS the checkout — no version comparison needed,
        and none is made."""
        repo = tmp_path / "mgf-fed"
        (repo / "src" / "mgf" / "fed").mkdir(parents=True)
        (repo / ".git").mkdir()
        import mgf.fed as _self

        real = _self.__file__
        try:
            _self.__file__ = str(repo / "src" / "mgf" / "fed" / "_doctor.py")
            ok, msg, _ = _doctor._installed_is_current(tmp_path)
        finally:
            _self.__file__ = real
        assert ok and "cannot lag" in msg

    def test_a_snapshot_at_the_same_version_still_says_it_may_lag(
        self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        """The defect this check exists for: code lands on main WITHOUT a version
        bump, so equal versions do not mean equal code. Reporting a bare ✓ here
        would recreate the blind spot in the check meant to close it."""
        repo = tmp_path / "mgf-fed"
        repo.mkdir()
        (repo / ".git").mkdir()
        from mgf.fed import __version__

        def fake_run(cmd, **_kw):
            out = f'[project]\nversion = "{__version__}"\n' if "show" in cmd else "abc1234"
            return subprocess.CompletedProcess(cmd, 0, out, "")

        monkeypatch.setattr(_doctor.subprocess, "run", fake_run)
        ok, msg, _ = _doctor._installed_is_current(tmp_path)
        assert ok
        assert "SNAPSHOT" in msg and "may still lag" in msg

    def test_a_version_mismatch_fails(
        self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        repo = tmp_path / "mgf-fed"
        repo.mkdir()
        (repo / ".git").mkdir()
        monkeypatch.setattr(
            _doctor.subprocess,
            "run",
            lambda cmd, **_k: subprocess.CompletedProcess(
                cmd, 0, '[project]\nversion = "99.99.99"\n' if "show" in cmd else "abc", ""
            ),
        )
        ok, _msg, fix = _doctor._installed_is_current(tmp_path)
        assert not ok and "uv tool install --force --editable" in fix

    def test_no_checkout_is_a_pass_with_the_reason(self, tmp_path: Path) -> None:
        """A self-check must not fail because a clone is absent — that would be
        its own false alarm."""
        ok, msg, _ = _doctor._installed_is_current(tmp_path)
        assert ok and "no mgf-fed checkout" in msg
