from __future__ import annotations

import os
from pathlib import Path
import unittest

import numpy as np

from ap1_m1_background_preflight import decode_hard_pass_state
from ap1_r2c_self_consistent_candidate import (
    CandidateConfig,
    classical_terms,
    run_candidate,
)


STATE = Path(os.environ["APEIRON_AP1_STATE_NPZ"])


class SelfConsistentCandidateTests(unittest.TestCase):
    def test_seed_local_kinetic_gates_are_positive(self):
        seed = decode_hard_pass_state(STATE)[-1, :5]
        terms = classical_terms(seed)
        self.assertGreater(terms["PX"], 0.0)
        self.assertGreater(terms["K"], 0.0)

    def test_bounded_pilot_preserves_claim_boundary(self):
        report = run_candidate(STATE, CandidateConfig(
            delta_N=1.0e-8, candidate_nodes=17, inherited_nodes=1025,
            fixed_point_steps=1, mode_nodes=8, digits=40,
        ))
        self.assertFalse(report["old_solver_or_physical_map_called"])
        self.assertTrue(report["diagnostics"]["finite"])
        self.assertTrue(report["diagnostics"]["positive_H"])
        self.assertIn("no H(z)", report["claim_boundary"])


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