"""Tests for the local-CI wrapper (woodpecker-cli exec)."""

from __future__ import annotations

import json
from pathlib import Path

import pytest

from mgf.fed import _localci
from mgf.fed._localci import run_local_ci


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")
    (tmp_path / "mgf-a").mkdir()
    return tmp_path


def test_no_woodpecker_cli(monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.setattr(_localci.shutil, "which", lambda _n: None)
    assert run_local_ci(["mgf-a"]) == 2


def test_skips_repo_without_woodpecker_file(
    tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
) -> None:
    # woodpecker-cli + docker both "present"
    monkeypatch.setattr(_localci.shutil, "which", lambda n: f"/usr/bin/{n}")
    rc = run_local_ci(["mgf-a"], root=_root(tmp_path))  # mgf-a has no .woodpecker.yml
    assert "no .woodpecker.yml" in capsys.readouterr().out
    assert rc == 0


def test_run_local_ci_pass_and_fail(
    tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
) -> None:
    monkeypatch.setattr(_localci.shutil, "which", lambda n: f"/usr/bin/{n}")
    root = _root(tmp_path)
    (root / "mgf-a" / ".woodpecker.yml").write_text("steps: []\n")

    class _P:
        returncode = 0
        stdout = "ok"
        stderr = ""

    monkeypatch.setattr(_localci.subprocess, "run", lambda *a, **k: _P())
    assert run_local_ci(["mgf-a"], root=root) == 0
    assert "PASS" in capsys.readouterr().out

    class _F:
        returncode = 1
        stdout = "fail-detail"
        stderr = ""

    monkeypatch.setattr(_localci.subprocess, "run", lambda *a, **k: _F())
    assert run_local_ci(["mgf-a"], root=root) == 1
