from __future__ import annotations

import json
import math
import os
from pathlib import Path
import tempfile
import unittest

import numpy as np

import ap1_m1_tachyonic_branch_boundary_preflight as preflight


ROOT = Path(os.environ.get("APEIRON_AP1_ROOT", Path(__file__).parents[2])).resolve()


class TachyonicBranchBoundaryPreflightTests(unittest.TestCase):
    def test_authorities_are_exact_and_failed_output_is_absent(self) -> None:
        report = preflight.verify_authorities(ROOT)
        self.assertTrue(report["all_preflight_gates_pass"])
        self.assertFalse(report["prospective_heldout_eligible"])
        self.assertFalse((ROOT / preflight.FAILED_RECOVERY_OUTPUT).exists())

    def test_plan_preserves_all_G32C_numerical_settings(self) -> None:
        plan = preflight.BranchBoundaryPlan()
        plan.validate()
        inherited = preflight.g32c.LogHRecoveryPlan()
        for name in (
            "qcut_over_Lambda",
            "adiabatic_support_stride",
            "adiabatic_momentum_support_nodes",
            "fixed_point_steps",
            "relaxation",
            "entry_nodes_per_panel",
            "tail_nodes_per_octave",
            "K_over_Lambda",
            "max_mode_step_N",
            "background_rtol",
            "decimal_low_digits",
            "decimal_high_digits",
        ):
            self.assertEqual(getattr(plan, name), getattr(inherited, name))

    def test_observed_bracket_is_exactly_one_coarse_panel(self) -> None:
        plan = preflight.BranchBoundaryPlan()
        self.assertTrue(
            math.isclose(
                plan.coarse_first_nonclosing_anchor_N
                - plan.coarse_last_contractive_anchor_N,
                plan.coarse_panel_step_N,
                rel_tol=0.0,
                abs_tol=4.0e-18,
            )
        )

    def test_all_anchors_align_on_coarse_middle_and_fine_grids(self) -> None:
        plan = preflight.BranchBoundaryPlan()
        for factor in plan.resolution_factors:
            counts = [plan.nodes(anchor, factor) for anchor in plan.continuation_anchor_N]
            self.assertEqual(counts, sorted(counts))
            self.assertEqual(len(counts), len(set(counts)))

    def test_resolution_panels_are_exactly_nested(self) -> None:
        plan = preflight.BranchBoundaryPlan()
        for anchor in plan.continuation_anchor_N:
            coarse = plan.nodes(anchor, 1) - 1
            middle = plan.nodes(anchor, 2) - 1
            fine = plan.nodes(anchor, 4) - 1
            self.assertEqual(middle, 2 * coarse)
            self.assertEqual(fine, 2 * middle)

    def test_invalid_resolution_is_rejected(self) -> None:
        with self.assertRaises(ValueError):
            preflight.BranchBoundaryPlan().panel_step(3)

    def test_h2_roundtrip_is_below_machine_canary_cap(self) -> None:
        canary = preflight.h2_equivalence_canary()
        self.assertLessEqual(
            canary["max_H_roundtrip_relative_defect"], preflight.CANARY_CAP
        )
        self.assertTrue(canary["positive_H_for_all_finite_positive_u_H_canaries"])

    def test_h2_rhs_reconstruction_is_below_machine_canary_cap(self) -> None:
        canary = preflight.h2_equivalence_canary()
        self.assertLessEqual(
            canary["max_RHS_reconstruction_relative_defect"],
            preflight.CANARY_CAP,
        )

    def test_h2_analytic_positive_branch_toy_is_exact_to_cap(self) -> None:
        canary = preflight.h2_equivalence_canary()
        self.assertLessEqual(
            canary["analytic_positive_H_toy_relative_defect"],
            preflight.CANARY_CAP,
        )

    def test_h2_chart_rejects_zero_negative_and_nonfinite_state(self) -> None:
        reference = 4.3e-7
        for value in (0.0, -1.0, math.nan, math.inf):
            state = np.array([0.0, 0.0, 0.0, 0.0, value])
            with self.assertRaises(preflight.TachyonicBranchBoundaryPreflightError):
                preflight.h2_to_physical_state(state, reference)

    def test_h2_and_logh_are_distinct_coordinates(self) -> None:
        self.assertNotEqual(preflight.H2_CHART, preflight.g32c.LOGH_CHART)

    def test_chi2_growth_profile_is_strictly_increasing_and_consumed(self) -> None:
        profile = preflight.NONBLIND_DIAGNOSTIC_AUDIT["first_map_chi2_profile"]
        values = [item["chi2_Mpl2"] for item in profile]
        self.assertTrue(all(right > left for left, right in zip(values, values[1:])))
        self.assertLessEqual(
            max(item["N"] for item in profile),
            preflight.BranchBoundaryPlan().consumed_domain_endpoint_N,
        )

    def test_failed_recovery_and_backtracking_are_not_pass_results(self) -> None:
        audit = preflight.NONBLIND_DIAGNOSTIC_AUDIT
        self.assertEqual(audit["G32C_bound_logH_recovery_pilot_attempts"], 1)
        self.assertEqual(audit["G32C_bound_logH_recovery_completed_resolution_levels"], 0)
        self.assertFalse(audit["G32C_bound_logH_recovery_report_written"])
        self.assertFalse(audit["G32C_bound_logH_recovery_checkpoint_or_seed_released"])
        self.assertFalse(audit["simple_branch_backtracking_full_pass"])

    def test_diagnostic_lower_is_pass_like_and_upper_is_explicit_nonpass(self) -> None:
        audit = preflight.NONBLIND_DIAGNOSTIC_AUDIT
        ceiling = preflight.g32.PREDECLARED_POLICY[
            "inherited_metric_freeze_policy"
        ]["max_fixed_point_source_gross_relative_change"]["ceiling"]
        self.assertLessEqual(
            audit["last_reproduced_contractive_anchor"]
            ["iteration_10_source_gross_relative_change"],
            ceiling,
        )
        self.assertTrue(
            audit["first_nonclosing_one_panel_extension"]
            ["iteration_2_background_result"].startswith("NONPASS")
        )

    def test_build_preflight_passes_all_gates_and_runs_no_background(self) -> None:
        report = preflight.build_preflight(ROOT)
        self.assertTrue(report["all_preflight_gates_pass"])
        self.assertTrue(all(report["gates"].values()))
        self.assertEqual(report["background_runs"], 0)
        self.assertEqual(report["physical_response_kernel_runs"], 0)
        self.assertTrue(report["branch_boundary_pilot_eligible"])
        self.assertFalse(report["prospective_heldout_eligible"])
        self.assertFalse(report["seed_released"])
        for name in (
            "AP1/CODE/ap1_m1_tachyonic_branch_boundary_preflight.py",
            "AP1/CODE/test_ap1_m1_tachyonic_branch_boundary_preflight.py",
        ):
            self.assertEqual(
                report["authority_sha256"][name],
                preflight.file_sha256(ROOT / name),
            )

    def test_plan_manifest_contains_both_charts_and_node_counts(self) -> None:
        manifest = preflight.plan_manifest(preflight.BranchBoundaryPlan())
        self.assertEqual(
            manifest["positive_branch_charts"],
            [preflight.g32c.LOGH_CHART, preflight.H2_CHART],
        )
        self.assertEqual(set(manifest["node_counts_by_resolution"]), {"1", "2", "4"})

    def test_pass_writer_refuses_nonpass_and_nan(self) -> None:
        with tempfile.TemporaryDirectory() as directory:
            nonpass = Path(directory) / "nonpass.json"
            with self.assertRaises(preflight.TachyonicBranchBoundaryPreflightError):
                preflight._write_pass_json(
                    {"all_preflight_gates_pass": False}, nonpass
                )
            self.assertFalse(nonpass.exists())
            invalid = Path(directory) / "invalid.json"
            with self.assertRaises(ValueError):
                preflight._write_pass_json(
                    {"all_preflight_gates_pass": True, "value": math.nan}, invalid
                )
            self.assertFalse(invalid.exists())

    def test_pass_writer_is_exclusive_and_strict_json(self) -> None:
        with tempfile.TemporaryDirectory() as directory:
            output = Path(directory) / "pass.json"
            report = {"all_preflight_gates_pass": True, "value": 1.0}
            preflight._write_pass_json(report, output)
            self.assertEqual(json.loads(output.read_text()), report)
            with self.assertRaises(FileExistsError):
                preflight._write_pass_json(report, output)

    def test_checkpoint_text_keeps_claim_boundary_locked(self) -> None:
        report = preflight.build_preflight(ROOT)
        text = preflight.checkpoint_markdown(report)
        self.assertIn("single-resolution diagnostic bracket", text)
        self.assertIn("remain locked", text)
        self.assertIn("zero backgrounds", text)


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