"""Quarantine honesty (M2 Wave-2, PLAN §1.4): a quarantined selection
is VISIBLE — one `quarantined` record (severity WARN) per excluded
test lands in run.jsonl, and `--quarantine-report` prints the table.
"""

from __future__ import annotations

import json
from typing import TYPE_CHECKING

from mgf.test_supervisor.__main__ import _print_quarantine_table
from mgf.test_supervisor.quarantine import QuarantineStore
from mgf.test_supervisor.records import now_iso, read_jsonl
from mgf.test_supervisor.supervisor import RunConfig, Supervisor

if TYPE_CHECKING:
    from pathlib import Path

    import pytest

_FLAKY = "tests/unit/test_x.py::test_flaky"


def _quarantine(gates_dir: Path, test_id: str) -> None:
    store = QuarantineStore(gates_dir / "quarantine.json")
    for _ in range(3):
        store.update_outcome(test_id, "failed", "boom", now_iso())
    assert store.all()[test_id].quarantined_at != ""
    store.save()


def test_quarantined_selection_emits_warn_records(tmp_path: Path) -> None:
    gates = tmp_path / ".gates"
    gates.mkdir()
    _quarantine(gates, _FLAKY)

    cfg = RunConfig(
        repo_root=tmp_path,
        gates_dir=gates,
        test_ids=[],  # nothing selected to actually run
        test_markers={_FLAKY: ("integration",)},
        run_id="q-run",
        pytest_cmd=["true"],
        quarantined_ids=(_FLAKY,),
    )
    Supervisor(cfg).run()

    records = list(read_jsonl(gates / "last-run" / "run.jsonl"))
    assert len(records) == 1
    rec = records[0]
    assert rec["test_id"] == _FLAKY
    assert rec["outcome"] == "quarantined"
    assert rec["severity"] == "WARN"  # unified with mgf.common.testing.DEFAULT_SEVERITY
    assert rec["code"] == "QUARANTINED"
    assert rec["tier"] == 2  # real marker-derived tier, not a placeholder
    assert rec["markers"] == ["integration"]
    assert rec["duration_ms"] == 0
    assert "boom" in (rec["detail"] or "")  # the last failure travels with the record
    assert rec["remediation"]  # a next step is always offered
    # The record is valid single-line JSON (the run.jsonl contract).
    assert json.loads(json.dumps(rec)) == rec


def test_no_quarantined_ids_emits_nothing(tmp_path: Path) -> None:
    gates = tmp_path / ".gates"
    gates.mkdir()
    cfg = RunConfig(
        repo_root=tmp_path,
        gates_dir=gates,
        test_ids=[],
        test_markers={},
        run_id="clean-run",
        pytest_cmd=["true"],
    )
    Supervisor(cfg).run()
    assert list(read_jsonl(gates / "last-run" / "run.jsonl")) == []


def test_quarantine_report_table(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:
    gates = tmp_path / ".gates"
    gates.mkdir()
    _quarantine(gates, _FLAKY)
    store = QuarantineStore(gates / "quarantine.json")
    # A watched-but-not-quarantined entry too.
    store.update_outcome("tests/unit/test_y.py::test_watched", "failed", "meh", now_iso())

    _print_quarantine_table(store)
    out = capsys.readouterr().out
    assert "quarantine report: 1 quarantined (WARN), 1 watching" in out
    assert "QUARANTINED" in out
    assert _FLAKY in out
    assert "watching" in out
    assert "tests/unit/test_y.py::test_watched" in out


def test_quarantine_report_empty(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:
    _print_quarantine_table(QuarantineStore(tmp_path / "quarantine.json"))
    assert "empty — no flaky tests tracked" in capsys.readouterr().out
