"""TS-01 — every src module has a test mirror (somewhere under tests/) OR an allow-list entry."""

from __future__ import annotations

from pathlib import Path

_TESTS = Path(__file__).resolve().parent
_PKG = _TESTS.parent / "src" / "mgf" / "vm" / "core"
_ALLOW = _TESTS / "MIRROR_ALLOWLIST.txt"
_TEST_STEMS = {p.stem for p in _TESTS.rglob("test_*.py")}


def _allow() -> set[str]:
    return (
        {
            ln.split("#")[0].strip()
            for ln in _ALLOW.read_text(encoding="utf-8").splitlines()
            if ln.split("#")[0].strip()
        }
        if _ALLOW.is_file()
        else set()
    )


def _has_mirror(stem: str) -> bool:
    return any(f"test_{s}" in _TEST_STEMS for s in {stem, stem.lstrip("_")})


def test_every_source_module_has_mirror_or_allowlist() -> None:
    allow = _allow()
    missing = [
        str(p.relative_to(_PKG))
        for p in _PKG.rglob("*.py")
        if "__pycache__" not in p.parts
        and p.name != "__init__.py"
        and p.name not in allow
        and not _has_mirror(p.stem)
    ]
    assert not missing, (
        f"TS-01: {len(missing)} modules with no test mirror and no allow-list entry: {missing[:15]}"
    )
