"""Repo-wide rules from the build prompt, enforced so they cannot silently regress."""
import re
from pathlib import Path

APP = Path(__file__).resolve().parents[1] / "app"
MIGRATIONS = Path(__file__).resolve().parents[1] / "migrations"


def _sources():
    for root in (APP, MIGRATIONS):
        for p in root.rglob("*.py"):
            yield p, p.read_text(encoding="utf-8")


def test_no_utcnow_anywhere():
    for p, text in _sources():
        assert "utcnow" not in text, p


def test_clock_is_the_only_place_that_reads_os_time():
    allowed = {"clock.py", "auth.py", "seed.py"}  # JWT expiry and seed's 'today' are not app time
    for p, text in _sources():
        if "datetime.now(" in text and p.name not in allowed:
            raise AssertionError(f"{p} reads OS time; use app.core.clock")


def test_no_markdown_sticker_or_code128_concepts():
    pattern = re.compile(r"markdown|sticker|code128|MARKDOWN", re.IGNORECASE)
    for p, text in _sources():
        if p.name == "test_conventions.py":
            continue
        for line in text.splitlines():
            if pattern.search(line):
                # Allowed only where we state that the concept is absent.
                assert re.search(r"\bno\b|not|never|without|instead", line, re.IGNORECASE), (
                    f"{p}: {line.strip()}")


def test_engines_do_not_touch_the_database():
    for p in (APP / "engines").rglob("*.py"):
        text = p.read_text(encoding="utf-8")
        assert "sqlalchemy" not in text and "app.core.database" not in text, p
