"""Tests for the static gate runner."""

from __future__ import annotations

import json
from pathlib import Path

import pytest

from mgf.fed import _gates
from mgf.fed._gates import GateResult, run_gates


def _root(tmp_path: Path) -> Path:
    reg = {
        "release_waves": [["mgf-a"]],
        "libraries": [{"repo": "mgf-a", "lang": "python", "version": "1.0.0"}],
    }
    (tmp_path / "mgf-standard").mkdir()
    (tmp_path / "mgf-standard" / "MGF_LIBRARIES.json").write_text(json.dumps(reg), encoding="utf-8")
    src = tmp_path / "mgf-a" / "src"
    src.mkdir(parents=True)
    (src / "x.py").write_text("x = 1\n", encoding="utf-8")
    return tmp_path


def test_gateresult_ok_logic() -> None:
    assert GateResult("r", True, True, "").ok
    assert GateResult("r", None, None, "").ok  # N/A counts as not-failing
    assert not GateResult("r", False, True, "x").ok
    assert not GateResult("r", True, False, "x").ok


def test_run_gates_all_pass(
    tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
) -> None:
    monkeypatch.setattr(_gates.shutil, "which", lambda _n: "/usr/bin/ruff")
    monkeypatch.setattr(_gates, "_run", lambda _args: (True, ""))
    assert run_gates(root=_root(tmp_path)) == 0
    assert "1 checked · 1 clean · 0 failing" in capsys.readouterr().out


def test_run_gates_reports_failure(
    tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
) -> None:
    monkeypatch.setattr(_gates.shutil, "which", lambda _n: "/usr/bin/ruff")
    monkeypatch.setattr(
        _gates, "_run", lambda args: (False, "x.py:1 E501") if "check" in args else (True, "")
    )
    assert run_gates(root=_root(tmp_path)) == 1
    assert "1 failing" in capsys.readouterr().out


def test_run_gates_no_ruff(monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.setattr(_gates, "_find_ruff", lambda: None)
    assert run_gates() == 2
