"""TS-01 / DP-05 — ``tests/`` mirrors ``src/`` 1:1.

Every source module under ``src/mgf/fastapi/`` MUST have a corresponding
``tests/unit/.../test_<name>.py`` mirror, OR a ``tests/MIRROR_ALLOWLIST.txt``
entry with a reason. A new source module added without either fails here —
the drift TS-01 prevents. ``__init__.py`` is exempt.
"""

from __future__ import annotations

from pathlib import Path

_TESTS = Path(__file__).resolve().parent
_PKG = _TESTS.parent / "src" / "mgf" / "fastapi"
_ALLOWLIST = _TESTS / "MIRROR_ALLOWLIST.txt"


def _allowlist() -> set[str]:
    if not _ALLOWLIST.is_file():
        return set()
    return {
        ln.strip()
        for ln in _ALLOWLIST.read_text(encoding="utf-8").splitlines()
        if ln.strip() and not ln.lstrip().startswith("#")
    }


def _candidate_mirrors(rel: Path) -> list[Path]:
    stems = {rel.stem, rel.stem.lstrip("_")}
    dirs = {_TESTS / "unit" / rel.parent, _TESTS / "unit"}
    return [d / f"test_{s}.py" for d in dirs for s in sorted(stems)]


def _source_modules() -> list[Path]:
    return [
        p for p in _PKG.rglob("*.py") if "__pycache__" not in p.parts and p.name != "__init__.py"
    ]


def test_every_source_module_has_a_mirror_or_allowlist_entry() -> None:
    allow = _allowlist()
    missing = [
        rel.as_posix()
        for src in _source_modules()
        for rel in [src.relative_to(_PKG)]
        if rel.as_posix() not in allow and not any(p.exists() for p in _candidate_mirrors(rel))
    ]
    assert not missing, (
        "TS-01: source modules with no test mirror and no MIRROR_ALLOWLIST entry: "
        f"{missing}. Add a tests/unit/test_<name>.py or an allow-list line with a reason."
    )
