import importlib.util
import json
import subprocess
import sys
import unittest
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]


def load_module():
    spec = importlib.util.spec_from_file_location(
        "dissect_llm_request", ROOT / "ops" / "dissect_llm_request.py"
    )
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module


def load_json_file(rel):
    return json.loads((ROOT / rel).read_text(encoding="utf-8"))


class DissectionKitTest(unittest.TestCase):
    def test_required_files_exist(self):
        for relative in [
            "README.md",
            "Makefile",
            "requirements.txt",
            "data/request_case.json",
            "data/toy_vocab.json",
            "contracts/dissection_policy.json",
            "ops/dissect_llm_request.py",
            "templates/entrega.md",
        ]:
            self.assertTrue((ROOT / relative).exists(), relative)

    def test_runner_generates_valid_report(self):
        subprocess.run(
            [sys.executable, "ops/dissect_llm_request.py", "--write", "--fail-on-invalid"],
            cwd=ROOT,
            check=True,
        )
        report = json.loads((ROOT / "output/dissection_report.json").read_text(encoding="utf-8"))
        self.assertTrue(report["gate_valid"], report.get("issues"))
        self.assertEqual(report["sampling"]["selected_first_token"], "{\"categoria\"")
        self.assertGreater(report["prompt_token_count"], 55)
        self.assertIn("kv_cache_gb", report["runtime"])
        self.assertIn("architecture_signals", report)
        self.assertEqual(report["architecture_signals"]["position_encoding"], "RoPE")
        self.assertGreater(report["runtime"]["gqa_kv_cache_saving_percent"], 0)
        self.assertGreater(report["runtime"]["speculative_speedup_toy"], 1)

    def test_markdown_contains_engineering_sections(self):
        subprocess.run([sys.executable, "ops/dissect_llm_request.py", "--write"], cwd=ROOT, check=True)
        text = (ROOT / "output/dissection_report.md").read_text(encoding="utf-8")
        for heading in [
            "## Tokenizacion",
            "## Formas de tensores",
            "## Arquitectura y runtime moderno",
            "## Logits y sampling",
            "## KV cache y runtime",
            "## Decision de ingenieria",
        ]:
            self.assertIn(heading, text)


class DissectionDomainTest(unittest.TestCase):
    def setUp(self):
        self.mod = load_module()
        self.report = self.mod.build_report(
            load_json_file("data/request_case.json"),
            load_json_file("data/toy_vocab.json"),
            load_json_file("contracts/dissection_policy.json"),
        )

    def test_weights_memory_4bit_8b(self):
        # 8B * 4 bits / 8 = 4 GB
        self.assertAlmostEqual(self.report["runtime"]["weights_gb"], 4.0, places=3)

    def test_kv_cache_gqa_and_full_mha(self):
        rt = self.report["runtime"]
        # GQA con 8 cabezas KV: 2*32*4*4096*8*128*2 bytes = 2,147 GB
        self.assertAlmostEqual(rt["kv_cache_gb"], 2.147, places=2)
        # MHA con 32 cabezas = 4x el de GQA
        self.assertAlmostEqual(rt["kv_cache_full_mha_gb"], 8.59, places=2)
        self.assertAlmostEqual(rt["kv_cache_full_mha_gb"], 4 * rt["kv_cache_gb"], places=1)
        self.assertAlmostEqual(rt["gqa_kv_cache_saving_percent"], 75.0, places=1)

    def test_speculative_speedup_consistent(self):
        rt = self.report["runtime"]
        self.assertAlmostEqual(rt["speculative_speedup_toy"], rt["decode_seconds_if_max_tokens"] / rt["speculative_decode_seconds_toy"], places=2)
        self.assertGreater(rt["speculative_speedup_toy"], 1.0)

    def test_tensor_shapes_reflect_gqa(self):
        shapes = self.report["tensor_shapes"]
        # q usa 32 cabezas de atención; k/v solo 8 (GQA)
        self.assertEqual(shapes["q"][1], 32)
        self.assertEqual(shapes["k_cache"][1], 8)
        self.assertEqual(shapes["embeddings"][2], 4096)

    def test_softmax_and_filters_are_distributions(self):
        probs = self.mod.softmax({"a": 2.0, "b": 1.0, "c": 0.0}, 1.0)
        self.assertAlmostEqual(sum(probs.values()), 1.0, places=9)
        top = self.mod.apply_top_k(probs, 2)
        self.assertEqual(len(top), 2)
        self.assertAlmostEqual(sum(top.values()), 1.0, places=9)

    def test_first_token_is_json_and_low_entropy(self):
        s = self.report["sampling"]
        self.assertEqual(s["selected_first_token"], "{\"categoria\"")
        self.assertLess(s["entropy_bits"], 1.7)
        self.assertAlmostEqual(s["entropy_bits"], 0.726, places=2)


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