from __future__ import annotations

import os
from pathlib import Path
import unittest

from ap1_r2c_high_precision_modes import build_high_precision_report, propagate_endpoint_decimal
from ap1_r2c_mode_inheritance import inherited_trajectory
from chi_background_closure import ChiParameters, physical_shells


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


class HighPrecisionModeTests(unittest.TestCase):
    def test_precision_floor_is_enforced(self):
        k, _ = physical_shells(ChiParameters().Lambda, nodes=4)
        with self.assertRaises(ValueError):
            propagate_endpoint_decimal(inherited_trajectory(STATE, 33), k, digits=20)

    def test_decimal_wronskian_passes_on_tachyonic_history(self):
        k, _ = physical_shells(ChiParameters().Lambda, nodes=4)
        result = propagate_endpoint_decimal(inherited_trajectory(STATE, 257), k, digits=50)
        self.assertLess(result["wronskian_relative_error"], 1.0e-30)

    def test_report_preserves_production_boundary(self):
        report = build_high_precision_report(STATE, levels=(129, 257), digits=50)
        self.assertTrue(report["gates"]["wronskian_below_1e_11"])
        self.assertTrue(report["gates"]["endpoint_refines_monotonically"])
        self.assertTrue(report["gates"]["completed_history_refines_monotonically"])
        self.assertFalse(report["old_solver_or_physical_map_called"])
        self.assertIn("source", report["claim_boundary"])

    def test_resolved_pv_endpoint_is_finite(self):
        k, weights = physical_shells(ChiParameters().Lambda, nodes=4)
        result = propagate_endpoint_decimal(
            inherited_trajectory(STATE, 129), k, weights, digits=50
        )
        self.assertTrue(all(
            abs(value) < float("inf")
            for value in result["resolved_pv_endpoint"].values()
        ))


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