"""Phase 6A — FRFM ID format conformance.

Locked decision (2026-05-18): both setup/SRS.md and setup/PRD.md use 3-digit
zero-padded FRFM identifiers (FRFM001, FRFM046, etc.) so reviewers can grep
SRS-to-code without ambiguity. This test fails the build if any future edit
re-introduces the legacy 2-digit form (FRFM04, FRFM46, etc.) inside the
FRFM table block of either document.
"""
from __future__ import annotations

import re
from pathlib import Path

import pytest

_REPO_ROOT = Path(__file__).resolve().parents[3]
_SRS_PATH = _REPO_ROOT / "setup" / "SRS.md"
_PRD_PATH = _REPO_ROOT / "setup" / "PRD.md"

# 2-digit FRFM token: FRFM followed by exactly two digits and a non-digit boundary
# (or end of line). This avoids matching FRFM046 etc.
_TWO_DIGIT_FRFM = re.compile(r"FRFM[0-9]{2}(?:[^0-9]|$)")


@pytest.mark.parametrize("path", [_SRS_PATH, _PRD_PATH])
def test_no_two_digit_frfm_ids(path: Path) -> None:
    text = path.read_text(encoding="utf-8")
    offenders: list[tuple[int, str]] = []
    for line_no, line in enumerate(text.splitlines(), start=1):
        for match in _TWO_DIGIT_FRFM.finditer(line):
            # Allow historical narrative mentions like "SRS previously used 2-digit IDs (FRFM04, ...)";
            # those appear in prose, not in the FRFM table row format.
            if "previously" in line.lower() or "historical" in line.lower():
                continue
            if "naming mismatch" in line.lower():
                continue
            offenders.append((line_no, match.group(0)))
    assert not offenders, (
        f"Found legacy 2-digit FRFM tokens in {path.name}: "
        + ", ".join(f"line {ln}: {tok}" for ln, tok in offenders[:10])
    )


def test_frfm_table_id_count() -> None:
    """The Phase 6A normalisation merged the duplicate FRFM05 into FRFM004, so the
    FRFM table now spans FRFM001-FRFM051 (50 unique IDs, one removed by merge)."""
    text = _SRS_PATH.read_text(encoding="utf-8")
    # Match 3-digit FRFM IDs in the body, dedupe.
    ids = set(re.findall(r"\bFRFM(\d{3})\b", text))
    # Drop the NFRFM hits (those use NFRFM prefix; \bFRFM only matches FRFM*).
    expected_subset = {f"{i:03d}" for i in (1, 2, 3, 4, 5, 6, 27, 46, 47, 50, 51)}
    missing = expected_subset - ids
    assert not missing, f"Expected FRFM IDs missing from SRS: {sorted(missing)}"
