"""PAPER-100 anti-drift gate: the Index of MUSTs must stay in lockstep with the Rules boxes.

Runs ``scripts/gen_rules_index.py --check`` — fails if any Rules-box rule is neither indexed
nor allowlisted as a SHOULD (the exact silent-omission P-A documented), and verifies the
committed ``rules.json`` companion is current.
"""

from __future__ import annotations

import json
import subprocess
import sys
from pathlib import Path

_ROOT = Path(__file__).resolve().parents[2]
_SCRIPT = _ROOT / "scripts" / "gen_rules_index.py"
_RULES_JSON = _ROOT / "docs" / "standards" / "rules.json"


def test_rules_index_gate_is_green() -> None:
    result = subprocess.run(
        [sys.executable, str(_SCRIPT), "--check"], capture_output=True, text=True, check=False
    )
    assert result.returncode == 0, result.stdout + result.stderr


def test_rules_json_is_current() -> None:
    # The committed companion must equal a fresh generation (no stale rules.json).
    before = json.loads(_RULES_JSON.read_text(encoding="utf-8"))
    subprocess.run([sys.executable, str(_SCRIPT)], capture_output=True, text=True, check=True)
    after = json.loads(_RULES_JSON.read_text(encoding="utf-8"))
    assert before == after, "rules.json is stale — run `python scripts/gen_rules_index.py`"
    assert after["counts"]["must"] == 265  # 264 + AP-16 (federation pin-window, API_DESIGN §4.4), 2026-07-01
