"""Extract the 100 snippets from README.md, syntax-check all of them, and run them if PyTorch is installed."""

import ast
import contextlib
import importlib.util
import io
import os
import re
import tempfile
import unittest
from pathlib import Path

README = Path(__file__).resolve().parent.parent / "README.md"
SNIPPET = re.compile(r"^### (\d+)\. (.+?)\n\n```python\n(.*?)\n```", re.S | re.M)
HAS_TORCH = importlib.util.find_spec("torch") is not None


def load_snippets():
    return [(int(n), title, code) for n, title, code in SNIPPET.findall(README.read_text())]


def missing_requirements(code):
    m = re.search(r"# requires: ([^#\n]+)", code)
    if not m:
        return []
    names = [part.strip().split()[0] for part in m.group(1).split(",")]
    return [n for n in names if importlib.util.find_spec(n) is None]


class SnippetTests(unittest.TestCase):
    snippets = load_snippets()

    def test_numbered_1_to_100(self):
        self.assertEqual([n for n, _, _ in self.snippets], list(range(1, 101)))

    def test_all_parse(self):
        for n, title, code in self.snippets:
            with self.subTest(snippet=n, title=title):
                ast.parse(code)

    def test_self_contained_imports(self):
        for n, title, code in self.snippets:
            if "torch" in code:
                with self.subTest(snippet=n):
                    self.assertRegex(code, r"(?m)^(import torch|from torch)")

    @unittest.skipUnless(HAS_TORCH, "PyTorch is not installed")
    def test_all_run(self):
        import torch

        for n, title, code in self.snippets:
            with self.subTest(snippet=n, title=title):
                if "skip-test" in code or missing_requirements(code):
                    continue  # syntax-checked only
                cwd = os.getcwd()
                with tempfile.TemporaryDirectory() as tmp:
                    os.chdir(tmp)
                    try:
                        with contextlib.redirect_stdout(io.StringIO()):
                            exec(compile(code, f"snippet_{n}", "exec"), {"__name__": f"snippet_{n}"})
                    finally:
                        os.chdir(cwd)
                        torch.use_deterministic_algorithms(False)


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