"""TESTING.md doc↔code tier-truth gate (M2 Wave-2 §1.3).

Pins ``scripts/check_testing_doc.py`` — invoked by ``gen_rules_index.py
--check`` — with a green live-repo run plus a seeded negative for every
drift class the M2 Wave-1 recon found in the wild: the integration
three-answers tier drift, the zombie ``slow``, the phantom
``functional``, and a deleted inline block.
"""

from __future__ import annotations

import importlib.util
import re
import subprocess
import sys
from pathlib import Path

_REPO_ROOT = Path(__file__).resolve().parents[2]
_SCRIPT = _REPO_ROOT / "scripts" / "check_testing_doc.py"
_DOC = _REPO_ROOT / "docs" / "standards" / "TESTING.md"


def _load_module():
    spec = importlib.util.spec_from_file_location("check_testing_doc", _SCRIPT)
    assert spec and spec.loader
    mod = importlib.util.module_from_spec(spec)
    sys.modules[spec.name] = mod
    spec.loader.exec_module(mod)
    return mod


ctd = _load_module()


class TestGreenPath:
    def test_live_repo_doc_is_green(self, capsys) -> None:
        assert ctd.check() == 0
        assert "TESTING-DOC GATE: GREEN" in capsys.readouterr().out

    def test_cli_form_is_green(self) -> None:
        proc = subprocess.run(
            [sys.executable, str(_SCRIPT)],
            capture_output=True,
            text=True,
            timeout=60,
            check=False,
        )
        assert proc.returncode == 0, proc.stdout + proc.stderr

    def test_table_parse_sees_e2e(self) -> None:
        # Regression: `e2e` carries a digit; a pure-alpha row regex
        # silently dropped it on the gate's very first run.
        table = ctd._parse_table(_DOC.read_text(encoding="utf-8"))
        assert table.get("e2e") == 3
        assert len(table) == 12


def _doctored(tmp_path: Path, mutate) -> Path:
    text = _DOC.read_text(encoding="utf-8")
    out = tmp_path / "TESTING.md"
    out.write_text(mutate(text), encoding="utf-8")
    return out


class TestSeededNegatives:
    def test_integration_tier_drift_is_red(self, tmp_path: Path, capsys) -> None:
        # THE Wave-1 finding: integration answered differently in
        # different places. Flip the block's value and the gate reds.
        doc = _doctored(tmp_path, lambda t: t.replace('"integration": 2,', '"integration": 1,'))
        assert ctd.check(doc) == 1
        assert "integration" in capsys.readouterr().err

    def test_zombie_slow_is_red(self, tmp_path: Path, capsys) -> None:
        doc = _doctored(tmp_path, lambda t: t.replace('"e2e": 3,', '"e2e": 3,\n    "slow": 3,'))
        assert ctd.check(doc) == 1
        assert "slow" in capsys.readouterr().err

    def test_phantom_functional_row_is_red(self, tmp_path: Path, capsys) -> None:
        doc = _doctored(
            tmp_path,
            lambda t: t.replace(
                "| `contract` | correctness@surface | tier-1 |",
                "| `functional` | correctness@unit | tier-1 | phantom returns |\n"
                "| `contract` | correctness@surface | tier-1 |",
            ),
        )
        assert ctd.check(doc) == 1
        assert "functional" in capsys.readouterr().err

    def test_missing_block_is_red(self, tmp_path: Path, capsys) -> None:
        doc = _doctored(tmp_path, lambda t: re.sub(r"MARKER_TIER = \{.*?\}", "", t, flags=re.S))
        assert ctd.check(doc) == 1
        assert "missing" in capsys.readouterr().err

    def test_table_vs_block_divergence_is_red(self, tmp_path: Path, capsys) -> None:
        # Table says tier-3 for concurrency, block says tier-2 →
        # internal doc split-brain must red even without mgf.common.
        doc = _doctored(
            tmp_path,
            lambda t: t.replace(
                "| `concurrency` | correctness@adversity | tier-2 |",
                "| `concurrency` | correctness@adversity | tier-3 |",
            ),
        )
        assert ctd.check(doc) == 1
        err = capsys.readouterr().err
        assert "concurrency" in err

    def test_unreadable_doc_is_red(self, tmp_path: Path, capsys) -> None:
        assert ctd.check(tmp_path / "nope.md") == 1
        assert "cannot read" in capsys.readouterr().err
