from __future__ import annotations

from copy import deepcopy
import json
import os
from pathlib import Path
import unittest

from ap1_m1_junction_128_seed import (
    Junction128SeedError,
    build_seed,
    validate_authorities,
)


ROOT = Path(os.environ["APEIRON_AP1_ROOT"])
HELDOUT = ROOT / "AP1/APEIRON_AP1_M1_EXACT_INITIAL_JUNCTION_128_HELDOUT_20260902T181054Z.json"
FREEZE = ROOT / "AP1/APEIRON_AP1_M1_EXACT_INITIAL_JUNCTION_128_TOLERANCES_20260902T181030Z.json"
REVALIDATION_CODE = ROOT / "AP1/CODE/ap1_m1_junction_128_revalidation.py"
SEED_CODE = ROOT / "AP1/CODE/ap1_m1_junction_128_seed.py"


class AP1M1Junction128SeedTests(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.heldout = json.loads(HELDOUT.read_text(encoding="utf-8"))
        cls.authorities = validate_authorities(
            ROOT,
            cls.heldout,
            HELDOUT,
            FREEZE,
            REVALIDATION_CODE,
            SEED_CODE,
        )
        cls.arrays, cls.report = build_seed(ROOT, cls.heldout, cls.authorities)

    def test_authority_chain_is_hash_bound(self):
        self.assertGreaterEqual(len(self.authorities), 5)

    def test_mutated_heldout_is_rejected(self):
        bad = deepcopy(self.heldout)
        bad["all_128_heldout_gates_pass"] = False
        with self.assertRaises(Junction128SeedError):
            validate_authorities(
                ROOT, bad, HELDOUT, FREEZE, REVALIDATION_CODE, SEED_CODE
            )

    def test_exact_128_by_4_mode_seed(self):
        self.assertEqual(self.arrays["omega2_Mpl2"].shape, (4, 128))
        self.assertEqual(self.report["mode_seed"]["momentum_nodes"], 128)

    def test_all_seed_gates_pass_before_write(self):
        self.assertTrue(self.report["all_seed_gates_pass"])
        self.assertTrue(all(self.report["gates"].values()))

    def test_seed_report_is_json_serializable(self):
        json.dumps(self.report)

    def test_background_and_kernel_remain_unstarted(self):
        self.assertFalse(self.report["new_AP1_M1_background_started"])
        self.assertFalse(self.report["physical_response_kernel_started"])


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