#!/usr/bin/env python3
"""Dependency-free CPU validator for the fail-closed parts of train_qlora.py.

It deliberately does not import torch, Transformers, PEFT or TRL and never
loads a checkpoint. Run it before a GPU smoke test.
"""
from __future__ import annotations

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


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


class Config:
    def __init__(self, model_type, architectures, text_type=""):
        self.model_type = model_type
        self.architectures = architectures
        self.text_config = type("TextConfig", (), {"model_type": text_type})()


class TrainQloraCpuTests(unittest.TestCase):
    def test_official_dense_and_moe_classification_are_separate(self):
        dense = Config("qwen3_5", ["Qwen3_5ForConditionalGeneration"])
        moe = Config("qwen3_5_moe", ["Qwen3_5MoeForConditionalGeneration"])
        self.assertEqual(MODULE.classify(dense, "auto"), "dense")
        self.assertEqual(MODULE.classify(moe, "auto"), "moe")
        with self.assertRaises(SystemExit):
            MODULE.classify(moe, "dense")

    def test_unsupported_architecture_fails_closed(self):
        with self.assertRaises(SystemExit):
            MODULE.classify(Config("llama", ["LlamaForCausalLM"]), "auto")

    def test_text_target_filter_excludes_vision_router_and_unknown(self):
        selected = MODULE.select_linear_target_names([
            "language_model.layers.0.self_attn.q_proj",
            "visual.vision_tower.layers.0.q_proj",
            "language_model.layers.0.mlp.router",
            "language_model.embed_tokens",
        ])
        self.assertEqual(selected, ["language_model.layers.0.self_attn.q_proj"])
        self.assertNotIn("visual.vision_tower.layers.0.q_proj", selected)
        self.assertNotIn("language_model.layers.0.mlp.router", selected)
        self.assertNotIn("embed_tokens", MODULE.ALLOWED_LINEAR_SUFFIXES)

    def test_jsonl_fixture_has_assistant_messages(self):
        fixture = SCRIPT.with_name("qlora_smoke.jsonl")
        rows = MODULE.read_jsonl(fixture)
        self.assertEqual(len(rows), 2)
        self.assertTrue(all(any(m["role"] == "assistant" for m in r["messages"]) for r in rows))

    def test_invalid_jsonl_fails_closed(self):
        with tempfile.TemporaryDirectory() as tmp:
            path = Path(tmp) / "bad.jsonl"
            path.write_text(json.dumps({"messages": [{"role": "user", "content": "no answer"}]}) + "\n", encoding="utf-8")
            with self.assertRaises(SystemExit):
                MODULE.read_jsonl(path)


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