#!/usr/bin/env python3
"""Offline tests: no network, model, GPU or third-party package."""
from __future__ import annotations

import importlib.util
import json
import tempfile
import unittest
from pathlib import Path

SCRIPT = Path(__file__).with_name("distill_answers.py")
SPEC = importlib.util.spec_from_file_location("distill_answers_under_test", SCRIPT)
MODULE = importlib.util.module_from_spec(SPEC)
assert SPEC and SPEC.loader
SPEC.loader.exec_module(MODULE)


class DistillAnswersCpuTests(unittest.TestCase):
    def test_fixture_filters_literal_and_never_calls_network(self):
        rows = MODULE.read_rows(SCRIPT.with_name("distill_fixture.jsonl"))
        result = MODULE.validate(rows, max_samples=8)
        self.assertEqual(result["checked"], 2)
        self.assertEqual(result["accepted"], 1)
        self.assertEqual(result["rejected"][0]["id"], "literal-reject")

    def test_non_stop_is_rejected(self):
        row = {"expected": "OK"}
        self.assertEqual(MODULE.check_answer(row, "OK", "length")[0], False)

    def test_generation_refuses_existing_output_before_key_or_network(self):
        rows = MODULE.read_rows(SCRIPT.with_name("distill_fixture.jsonl"))
        with tempfile.TemporaryDirectory() as tmp:
            output = Path(tmp) / "existing.jsonl"
            output.write_text("sentinel\n", encoding="utf-8")
            args = type("Args", (), {
                "output": output, "base": "http://127.0.0.1:1/v1",
                "model": "teacher", "max_samples": 1, "max_tokens": 10,
            })()
            with self.assertRaises(SystemExit):
                MODULE.generate(rows, args)
            self.assertEqual(output.read_text(encoding="utf-8"), "sentinel\n")


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