"""Checks every template with a real gitignore matcher (pathspec's GitIgnoreSpec).

Run: uv run --with pathspec python -m unittest discover -s tests
"""
import subprocess
import sys
import unittest
from pathlib import Path

import pathspec

ROOT = Path(__file__).resolve().parent.parent
T = ROOT / "templates"


def spec(*names: str) -> pathspec.GitIgnoreSpec:
    lines: list[str] = []
    for n in names:
        lines += (T / f"{n}.gitignore").read_text().splitlines()
    return pathspec.GitIgnoreSpec.from_lines(lines)


CASES = {
    "Secrets": (
        [".env", ".env.local", ".env.production", "certs/server.pem", "credentials.json",
         "service-account-prod.json", ".streamlit/secrets.toml", "kaggle.json"],
        [".env.example", ".env.sample", ".env.template", "src/env.py", "README.md"],
    ),
    "Python": (
        ["__pycache__/x.cpython-313.pyc", "pkg/__pycache__/a.pyc", ".venv/bin/python", "dist/a.whl",
         ".ruff_cache/x", ".coverage"],
        ["src/pkg/__init__.py", "pyproject.toml", "uv.lock"],
    ),
    "Jupyter": (
        [".ipynb_checkpoints/a-checkpoint.ipynb", "notebooks/.ipynb_checkpoints/b.ipynb", "__marimo__/x"],
        ["notebooks/explore.ipynb"],
    ),
    "Model-Weights": (
        ["model.safetensors", "out/pytorch_model.bin", "ckpt/epoch=1.ckpt", "llama-3.Q4_K_M.gguf",
         "models/bert/config.json", "checkpoints/last.pt", "runs/x/checkpoint-500/optimizer.pt",
         "export/model.onnx", "clf.joblib", "export/saved_model/saved_model.pb"],
        ["models/.gitkeep", "models/README.md", "src/app/models/user.py", "src/train.py",
         "configs/model.yaml"],
    ),
    "Data": (
        ["data/raw/train.csv", "data/processed/x.parquet", "datasets/imagenet/a.jpg",
         "features.parquet", "emb.npy", "corpus.tar.gz"],
        ["data/.gitkeep", "data/README.md", "data/sample/tiny.csv", "src/data/loader.py",
         "tests/fixtures/small.json"],
    ),
    "Experiment-Tracking": (
        ["wandb/run-1/files/config.yaml", "mlruns/0/meta.yaml", "lightning_logs/version_0/hparams.yaml",
         "runs/Dec01/events.out.tfevents.1", "outputs/2026-12-01/12-00-00/.hydra/config.yaml",
         "dvclive/metrics.json", "trainer_output/checkpoint-10/x"],
        ["src/runs/__init__.py", "configs/outputs.yaml", "src/app/outputs/render.py"],
    ),
    "LLM-Apps": (
        ["chroma/chroma.sqlite3", "index.faiss", "storage/docstore.json", ".langchain.db",
         ".gradio/flagged/log.csv", "lancedb/t.lance/data", ".cache/x"],
        ["src/app/storage/s3.py", "src/rag/chroma.py", "prompts/system.md"],
    ),
    "AI-Agents": (
        [".claude/settings.local.json", "CLAUDE.local.md", ".claude/worktrees/feat/README.md",
         ".gemini/.env", ".gemini/worktrees/x/a.py", ".aider.chat.history.md",
         ".aider.input.history", ".aider.tags.cache.v4/cache.db", ".specstory/history/a.md"],
        ["CLAUDE.md", "AGENTS.md", ".claude/settings.json", ".claude/skills/x/SKILL.md",
         ".claude/agents/reviewer.md", ".mcp.json", ".cursor/rules/style.mdc",
         ".gemini/settings.json", ".codex/config.toml", ".github/copilot-instructions.md",
         ".aider.conf.yml"],
    ),
}


class TemplateTests(unittest.TestCase):
    def test_cases(self) -> None:
        for name, (ignored, kept) in CASES.items():
            s = spec(name)
            for p in ignored:
                with self.subTest(template=name, path=p, expect="ignored"):
                    self.assertTrue(s.match_file(p))
            for p in kept:
                with self.subTest(template=name, path=p, expect="kept"):
                    self.assertFalse(s.match_file(p))

    def test_every_template_has_cases(self) -> None:
        self.assertEqual(sorted(CASES), sorted(p.stem for p in T.glob("*.gitignore")))

    def test_combined_keeps_shared_agent_config_and_code(self) -> None:
        s = pathspec.GitIgnoreSpec.from_lines((ROOT / "AI.gitignore").read_text().splitlines())
        for p in ["CLAUDE.md", ".claude/settings.json", ".env.example", "src/app/models/user.py",
                  "pyproject.toml", "notebooks/a.ipynb", "data/sample/x.csv"]:
            self.assertFalse(s.match_file(p), p)
        for p in [".env", "model.safetensors", "wandb/x", ".claude/settings.local.json"]:
            self.assertTrue(s.match_file(p), p)

    def test_combined_file_is_up_to_date(self) -> None:
        out = subprocess.run([sys.executable, str(ROOT / "scripts/combine.py"), "--all"],
                             capture_output=True, text=True, check=True).stdout
        self.assertEqual(out, (ROOT / "AI.gitignore").read_text())

    def test_lint(self) -> None:
        for path in [*T.glob("*.gitignore"), ROOT / "global/gitignore_global"]:
            lines = path.read_text().splitlines()
            pats = [l for l in lines if l.strip() and not l.startswith("#")]
            self.assertEqual(len(pats), len(set(pats)), f"duplicates in {path.name}")
            for l in lines:
                self.assertEqual(l, l.rstrip(), f"trailing space in {path.name}: {l!r}")


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