"""PR-* test plan T7 — structural validator for the conformance
tracker's PR-* section.

PR-07 says: trackers MUST classify PR-* rows per the audit-
outcomes taxonomy (✅ / ❌ / ⚪ / 🚫 / ⏳ / N/A). This test
parses the tracker file and asserts:

  1. The PR-* section heading exists.
  2. Every row in that section uses a recognised status marker.
  3. Rows marked ✅ have rationale text citing either a file:line,
     test name, contract name, or commit SHA — pure ✅ without
     evidence is the falsification anti-pattern.

This is the test-side complement to the S9 ``audit_pr_conformance.py``
script (which cross-checks against live lint-imports); this test
validates SHAPE alone — does the tracker say things the right way.
"""

from __future__ import annotations

import re
from pathlib import Path

import pytest

pytestmark = pytest.mark.conformance

REPO = Path(__file__).resolve().parents[2]
TRACKER = REPO / "docs/inprogress/MGF_STANDARDS_CONFORMANCE.md"

# Recognised status markers (PR-07 ratifies the audit-outcomes taxonomy).
_VALID_STATUS_MARKERS = {"✅", "❌", "⚪", "🚫", "⏳", "N/A"}


def _extract_pr_section(text: str) -> str:
    """Return just the PR — PRESENTATION_LAYER section's body."""
    # Find the heading; section runs until the next §2.X heading
    # OR the next top-level "---" separator.
    m = re.search(
        r"###\s+§2\.\d+\s+PR\s+—\s+PRESENTATION_LAYER.*?(?=###\s+§2\.\d+|\Z|---\n)",
        text,
        re.DOTALL,
    )
    return m.group(0) if m else ""


def test_tracker_pr_section_exists() -> None:
    assert TRACKER.exists(), f"tracker missing: {TRACKER}"
    section = _extract_pr_section(TRACKER.read_text(encoding="utf-8"))
    assert section, (
        "no `### §2.X PR — PRESENTATION_LAYER` section in the tracker; "
        "PR-07 requires every project that meets PR-* applicability "
        "to classify its rows."
    )


def test_tracker_pr_rows_use_valid_status_markers() -> None:
    section = _extract_pr_section(TRACKER.read_text(encoding="utf-8"))
    assert section, "no PR section to inspect"
    # Tracker rows look like: | PR-01 ... | ✅ | rationale ... |
    rows = re.findall(r"^\|\s*(PR-\d+)\b[^|]*\|\s*([^|]+?)\s*\|", section, re.MULTILINE)
    assert rows, "PR section has no `| PR-NN | status | ... |` rows"
    for pr_id, status_cell in rows:
        # Extract the first recognised marker from the cell.
        found_markers = [m for m in _VALID_STATUS_MARKERS if m in status_cell]
        assert found_markers, (
            f"{pr_id} status cell {status_cell!r} doesn't contain any "
            f"recognised marker. Valid: {sorted(_VALID_STATUS_MARKERS)}"
        )


def test_tracker_pr_passing_rows_cite_evidence() -> None:
    """Rows marked ✅ MUST cite evidence — file path, test name,
    or contract name. A bare ✅ without rationale is the
    falsification pattern PR-07 guards against."""
    section = _extract_pr_section(TRACKER.read_text(encoding="utf-8"))
    rows = re.findall(
        r"^\|\s*(PR-\d+)\b[^|]*\|\s*([^|]+?)\s*\|\s*([^|]+?)\s*\|",
        section,
        re.MULTILINE,
    )
    evidence_pattern = re.compile(
        # Path-like, test_*, contract-name (quoted), commit SHA (6+ hex), filename.ext,
        # or self-reference (PR-07 is its own evidence — the section IS the row).
        r"(\.py\b|\.toml\b|\.md\b|\bsrc/|\btests/|test_\w+|/\w+|"
        r"`[^`]+`|\b[0-9a-f]{6,}\b|import-linter|lint-imports|"
        r"this section|this file)",
        re.IGNORECASE,
    )
    failures: list[str] = []
    for pr_id, status_cell, rationale_cell in rows:
        if "✅" not in status_cell:
            continue
        if not evidence_pattern.search(rationale_cell):
            failures.append(
                f"{pr_id}: ✅ but rationale lacks evidence "
                f"(no file path / test / contract name): {rationale_cell!r}"
            )
    assert not failures, "PR-07 says ✅ rows MUST cite evidence. Falsification risk:\n" + "\n".join(
        failures
    )
