#!/usr/bin/env python3
"""Focused drift tests for deterministic documentation exports."""

from __future__ import annotations

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

ROOT = Path(__file__).resolve().parents[1]
sys.dont_write_bytecode = True
MODULE_PATH = ROOT / "ci" / "docs" / "build-docs.py"
SPEC = importlib.util.spec_from_file_location("build_docs", MODULE_PATH)
assert SPEC is not None and SPEC.loader is not None
build_docs = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(build_docs)


def fixture() -> tempfile.TemporaryDirectory[str]:
    work = tempfile.TemporaryDirectory()
    root = Path(work.name)
    shutil.copytree(ROOT / "docs-site" / "src", root / "docs-site" / "src")
    return work


# [unit->REQ-DOCS-PUBLISH-GATE]
class DocsDriftTests(unittest.TestCase):
    def test_checked_in_export_matches_sources(self) -> None:
        build_docs.check_generated_export(ROOT)

    def test_source_change_without_regeneration_is_rejected(self) -> None:
        with fixture() as work:
            root = Path(work)
            build_docs.write_generated_export(root)
            build_docs.check_generated_export(root)
            introduction = root / "docs-site" / "src" / "introduction.md"
            introduction.write_text(
                introduction.read_text(encoding="utf-8") + "\nUnexported change.\n",
                encoding="utf-8",
                newline="\n",
            )
            with self.assertRaisesRegex(build_docs.DocsError, "documentation drift"):
                build_docs.check_generated_export(root)

    def test_summary_missing_chapter_is_rejected(self) -> None:
        with fixture() as work:
            root = Path(work)
            summary = root / "docs-site" / "src" / "SUMMARY.md"
            summary.write_text(
                summary.read_text(encoding="utf-8") + "\n- [Missing](./missing.md)\n",
                encoding="utf-8",
                newline="\n",
            )
            with self.assertRaisesRegex(build_docs.DocsError, "does not exist"):
                build_docs.render_llms_full(root)


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