"""The tool's version must move when the bytes it ships move.

WHY THIS IS A TEST AND NOT A CONVENTION
=======================================

`pyproject.toml` said `version = "0.2.0"` from the day this package was created.
Across the seven commits that touched `trillboards_detector/labels.py` the model
vocabulary went 16,129 -> 37,321 bytes, one model id to eight, and the version
never moved once. Every one of those commits had an author who could have bumped
it; nothing asked, so nobody did.

That is not bookkeeping. Measured on uv 0.9.2, with the version held constant, a
change to a module under `trillboards_detector/` survives BOTH
`uv tool install` and `uv tool install --force` — uv's local-directory build
cache is not keyed on the package sources — and both print
"Installed 1 executable". A box therefore keeps an obsolete class VOCABULARY,
a granted specialist answers 400, and `/health` says `ready` throughout
(`.claude/lessons/2026-09-02-a-granted-model-is-not-a-served-model.md`).

So the version's local segment is DERIVED from the shipped bytes, and this file
is what makes forgetting impossible.
"""

from __future__ import annotations

import importlib.util
import re
import shutil
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path

DETECTOR_DIR = Path(__file__).resolve().parents[1]
STAMPER = DETECTOR_DIR / "stamp_version.py"
PYPROJECT = DETECTOR_DIR / "pyproject.toml"
PACKAGE_DIR = DETECTOR_DIR / "trillboards_detector"

sys.path.insert(0, str(DETECTOR_DIR))


def _load_stamper(root: Path):
    """Import `stamp_version` bound to `root` rather than to the real tree.

    Loaded as a FRESH module object per root so the mutation test below cannot
    be answered by a cached module still pointing at the committed sources —
    which is the same class of staleness this whole file exists to catch, and it
    would make the non-vacuity check vacuous.
    """
    spec = importlib.util.spec_from_file_location(f"stamp_version_{abs(hash(str(root)))}", root / "stamp_version.py")
    module = importlib.util.module_from_spec(spec)
    assert spec.loader is not None
    spec.loader.exec_module(module)
    return module


class TestVersionStamp(unittest.TestCase):
    def test_the_committed_stamp_matches_the_committed_bytes(self) -> None:
        """The check CI runs. Fails loudly with the one command that fixes it."""
        result = subprocess.run(
            [sys.executable, str(STAMPER), "--check"],
            capture_output=True,
            text=True,
        )
        self.assertEqual(
            result.returncode,
            0,
            "the detector's version stamp is stale:\n"
            f"{result.stdout}{result.stderr}",
        )

    def test_pyproject_and_the_module_carry_the_same_version(self) -> None:
        """Two writers, and they must never disagree.

        `pyproject.toml` carries the literal because uv reads the version FROM
        THIS FILE to decide whether its cached wheel still describes the
        directory — a hatch dynamic version would be read only by BUILDING,
        which is the step a cache hit skips, so it could never invalidate its own
        cache. `_version.py` carries it because the running service has to be
        able to say what it is without importing package metadata. Both are
        written by one generator; this asserts the generator is the only writer.
        """
        stamper = _load_stamper(DETECTOR_DIR)
        self.assertEqual(stamper.read_pyproject_version(), stamper.read_stamped_version())

    def test_the_package_exports_the_stamped_version(self) -> None:
        import trillboards_detector
        from trillboards_detector import _version

        self.assertEqual(trillboards_detector.__version__, _version.VERSION)
        self.assertEqual(_version.VERSION, f"{_version.BASE_VERSION}+src.{_version.SOURCE_FINGERPRINT}")

    def test_the_version_carries_a_source_fingerprint(self) -> None:
        """`0.2.0` and `0.2.0` were two different builds. `+src.<hex>` cannot be."""
        from trillboards_detector import _version

        self.assertRegex(_version.VERSION, r"^\d+\.\d+\.\d+\+src\.[0-9a-f]{12}$")

    def test_editing_a_shipped_module_moves_the_fingerprint(self) -> None:
        """NON-VACUITY. A check that cannot go red is not a check.

        Copies the package to a temp tree, appends one line to the file whose
        growth started all this, and asserts the derived version changes. This is
        the property the whole design rests on, asserted rather than assumed.
        """
        with tempfile.TemporaryDirectory() as tmp:
            root = Path(tmp) / "detector"
            shutil.copytree(
                DETECTOR_DIR,
                root,
                ignore=shutil.ignore_patterns("__pycache__", "bench", "tests", "*.pyc"),
            )
            before = _load_stamper(root).expected_version()[2]

            labels = root / "trillboards_detector" / "labels.py"
            labels.write_text(labels.read_text() + "\n# one more model id\n", encoding="utf-8")
            after = _load_stamper(root).expected_version()[2]

            self.assertNotEqual(before, after, "a shipped-module edit left the version unchanged")

    def test_the_fingerprint_ignores_line_endings(self) -> None:
        """A Windows checkout must not stamp differently from the Linux one.

        `core.autocrlf=true` rewrites every checked-out `.py`. Without
        normalisation the stamp would flap per PLATFORM rather than per change,
        and a CI check on one OS would fail a tree that is correct on the other.
        """
        with tempfile.TemporaryDirectory() as tmp:
            root = Path(tmp) / "detector"
            shutil.copytree(
                DETECTOR_DIR,
                root,
                ignore=shutil.ignore_patterns("__pycache__", "bench", "tests", "*.pyc"),
            )
            before = _load_stamper(root).expected_version()[2]
            for path in list((root / "trillboards_detector").rglob("*.py")) + [root / "pyproject.toml"]:
                path.write_bytes(path.read_bytes().replace(b"\n", b"\r\n"))
            after = _load_stamper(root).expected_version()[2]
            self.assertEqual(before, after, "CRLF alone moved the fingerprint")

    def test_the_stamper_is_idempotent(self) -> None:
        """`--write` on a stamped tree changes nothing, so it is safe in a loop."""
        with tempfile.TemporaryDirectory() as tmp:
            root = Path(tmp) / "detector"
            shutil.copytree(
                DETECTOR_DIR,
                root,
                ignore=shutil.ignore_patterns("__pycache__", "bench", "tests", "*.pyc"),
            )
            stamper = _load_stamper(root)
            first_version, first_changed = stamper.write_stamp()
            second_version, second_changed = stamper.write_stamp()
            self.assertFalse(first_changed, "the committed tree was not already stamped")
            self.assertFalse(second_changed)
            self.assertEqual(first_version, second_version)

    def test_the_version_line_is_excluded_from_its_own_input(self) -> None:
        """Otherwise the stamp has no fixed point and `--write` never converges."""
        with tempfile.TemporaryDirectory() as tmp:
            root = Path(tmp) / "detector"
            shutil.copytree(
                DETECTOR_DIR,
                root,
                ignore=shutil.ignore_patterns("__pycache__", "bench", "tests", "*.pyc"),
            )
            stamper = _load_stamper(root)
            before = stamper.compute_fingerprint()
            pyproject = root / "pyproject.toml"
            pyproject.write_text(
                re.sub(
                    r'^version\s*=\s*".*"\s*$',
                    'version = "9.9.9+src.deadbeefcafe"',
                    pyproject.read_text(encoding="utf-8"),
                    count=1,
                    flags=re.MULTILINE,
                ),
                encoding="utf-8",
            )
            self.assertEqual(before, stamper.compute_fingerprint())

    def test_a_dependency_pin_change_moves_the_fingerprint(self) -> None:
        """The pinned runtime is part of what this tool IS.

        `docs/runbooks/cctv-detector-tier.md` §2 picks this detector on a
        measured ~63 ms and says ORT's kernel fusion, thread heuristics and SIMD
        dispatch move between minor releases — so a box on a different
        onnxruntime is a box the measurement does not describe, and an installer
        must not mistake it for one it already has.
        """
        with tempfile.TemporaryDirectory() as tmp:
            root = Path(tmp) / "detector"
            shutil.copytree(
                DETECTOR_DIR,
                root,
                ignore=shutil.ignore_patterns("__pycache__", "bench", "tests", "*.pyc"),
            )
            before = _load_stamper(root).expected_version()[2]
            pyproject = root / "pyproject.toml"
            pyproject.write_text(
                pyproject.read_text(encoding="utf-8").replace(
                    '"onnxruntime==1.29.0"', '"onnxruntime==1.30.0"'
                ),
                encoding="utf-8",
            )
            self.assertNotEqual(before, _load_stamper(root).expected_version()[2])


class TestInstallersCannotAcceptAStaleInstall(unittest.TestCase):
    """`--force` is not enough, and all three installers used exactly `--force`.

    Measured on uv 0.9.2 (2026-09-04), local-directory source, `labels.py`-only
    change with `pyproject.toml` untouched:

        uv tool install <dir>                              STALE ("Audited 1 package")
        uv tool install --force <dir>                      STALE (cached wheel)
        uv tool install --force --refresh-package <name>   fresh

    So the flag is load-bearing, and so is asking the installed binary what it
    is afterwards. Asserted on the shipped text of all three provisioners
    because there is no runner on which all three can be executed.
    """

    INSTALLERS = (
        DETECTOR_DIR.parent / "macos" / "scripts" / "setup-detector.sh",
        DETECTOR_DIR.parent / "systemd" / "setup-detector.sh",
        DETECTOR_DIR.parent / "windows" / "setup-detector.ps1",
    )

    @staticmethod
    def _install_invocations(text: str) -> "list[str]":
        """Lines that actually RUN the install, not lines that mention it.

        Keyed on `--managed-python`, which every real invocation carries and no
        prose line does. A looser rule (any line containing "tool install")
        matches a log message and a PowerShell block comment, and a rule that
        matched nothing would pass vacuously — hence the count assertion at the
        call site.
        """
        return [line for line in text.splitlines() if "tool install" in line and "--managed-python" in line]

    def test_every_installer_busts_the_package_cache(self) -> None:
        for path in self.INSTALLERS:
            with self.subTest(installer=path.name + f" ({path.parent.name})"):
                text = path.read_text(encoding="utf-8")
                install_lines = self._install_invocations(text)
                # TWO: the ordinary install, and the uninstall-and-retry repair
                # rung. A file that grew a third would be installing somewhere
                # this test never looked.
                self.assertEqual(
                    len(install_lines),
                    2,
                    f"{path} runs {len(install_lines)} `uv tool install` invocations, expected 2",
                )
                for line in install_lines:
                    self.assertIn(
                        "--refresh-package trillboards-detector",
                        line,
                        f"{path} installs without busting uv's cached wheel: {line.strip()}",
                    )

    def test_every_installer_verifies_what_it_installed(self) -> None:
        for path in self.INSTALLERS:
            with self.subTest(installer=path.name + f" ({path.parent.name})"):
                text = path.read_text(encoding="utf-8")
                self.assertIn("--version", text, f"{path} never asks the binary what it is")
                self.assertIn(
                    "is STALE after a full reinstall",
                    text,
                    f"{path} has no loud outcome for an install that did not take",
                )

    def test_no_installer_uses_the_blunt_refresh(self) -> None:
        """`--refresh` re-downloads the pinned ~250 MB onnxruntime wheel every run."""
        for path in self.INSTALLERS:
            with self.subTest(installer=path.name + f" ({path.parent.name})"):
                for line in self._install_invocations(path.read_text(encoding="utf-8")):
                    self.assertNotRegex(line, r"--refresh(?!-package)\b")


if __name__ == "__main__":
    unittest.main()
