"""G32D fail-closed preflight for the AP1-M1 positive-H branch boundary.

The G32C-bound log-H recovery pilot was attempted once on the already
consumed N <= 0.10 domain.  It stopped before completing the coarse level and
wrote no report, checkpoint, trajectory, or seed.  Non-blind diagnostics then
identified tachyonic chi growth and bracketed the last coarse-grid
contractive continuation anchor between N=0.09953125 and N=0.099609375.

This module does not run a background.  It predeclares a multiresolution
branch-existence audit and an independent positive-branch coordinate

    u_H = (H / H_reference)^2,  H = H_reference * sqrt(u_H),

to cross-check the log-H coordinate without changing the physical H equation.
The future N=0.105..0.12 heldout remains unseen and locked.  Equations,
physics, parameters, counterterms, PV sectors, moving split, mode transport,
fixed-point count, relaxation, and all existing gate ceilings remain fixed.
"""
from __future__ import annotations

import argparse
from dataclasses import asdict, dataclass
from datetime import datetime, timezone
from hashlib import sha256
import json
import math
from pathlib import Path
from typing import Any

import numpy as np

import ap1_m1_balanced_coupled_stage_preflight as g32
import ap1_m1_logh_positive_branch_recovery_preflight as g32c


EXPECTED_AUTHORITIES = {
    "AP1/APEIRON_AP1_M1_LOGH_POSITIVE_BRANCH_RECOVERY_PREFLIGHT_LATEST.json": (
        "c25bff80552343198987c4c324c38ad2e696b3870ea7fa6f09ea944d2f1a8fd1"
    ),
    "AP1/APEIRON_AP1_M1_LOGH_POSITIVE_BRANCH_RECOVERY_PREFLIGHT_CHECKPOINT_LATEST.md": (
        "9282b1dfdbb03b32b88201c4bff8f653292dc6fa204a66e55de9924efc0f20f5"
    ),
    "AP1/CODE/ap1_m1_logh_positive_branch_recovery_preflight.py": (
        "1096e20e94bc60bdd0d484c3c940c207c83a7dadec2ba3a8db93cc626b839695"
    ),
    "AP1/CODE/test_ap1_m1_logh_positive_branch_recovery_preflight.py": (
        "43ed61f5c628701d3653820dbf477370ebfa75ee1a55e6e7f33c0aafa7e89091"
    ),
    "AP1/CODE/ap1_m1_logh_recovery_pilot.py": (
        "d5e8199bc8c253412a07e173c07f880365eccb99d549708b46b2465e00776bce"
    ),
    "AP1/CODE/test_ap1_m1_logh_recovery_pilot.py": (
        "64a06a9f766e7f5a0dc32fe8df81ce6f18ff9bd5b2dc35e1c7d258d8fcbe5636"
    ),
}

FAILED_RECOVERY_OUTPUT = (
    "AP1/APEIRON_AP1_M1_LOGH_RECOVERY_PILOT_20260903T064426Z.json"
)
H2_CHART = "u_H=(H/H_reference)^2, H=H_reference*sqrt(u_H)"
CANARY_CAP = float(64.0 * np.finfo(float).eps)


class TachyonicBranchBoundaryPreflightError(RuntimeError):
    """An authority, chronology, equivalence, or lock gate failed."""


@dataclass(frozen=True)
class BranchBoundaryPlan:
    """Resolution-nested, non-blind positive-branch existence audit."""

    consumed_domain_endpoint_N: float = 0.10
    continuation_scan_start_N: float = 0.099375
    coarse_last_contractive_anchor_N: float = 0.09953125
    coarse_first_nonclosing_anchor_N: float = 0.099609375
    coarse_panel_step_N: float = 0.000078125
    continuation_anchor_N: tuple[float, ...] = (
        0.090,
        0.095,
        0.0975,
        0.09875,
        0.099375,
        0.099453125,
        0.09953125,
        0.099609375,
    )
    resolution_factors: tuple[int, ...] = (1, 2, 4)
    qcut_over_Lambda: float = 0.6
    adiabatic_support_stride: int = 1
    adiabatic_momentum_support_nodes: int = 257
    fixed_point_steps: int = 10
    relaxation: float = 0.9
    entry_nodes_per_panel: int = 2
    tail_nodes_per_octave: int = 4
    K_over_Lambda: float = 64.0
    max_mode_step_N: float = 1.25e-5
    background_rtol: float = 2.0e-10
    decimal_low_digits: int = 60
    decimal_high_digits: int = 80
    prospective_heldout_evaluation_start_N: float = 0.105
    prospective_heldout_endpoint_N: float = 0.12

    def panel_step(self, factor: int) -> float:
        if factor not in self.resolution_factors:
            raise ValueError("unregistered branch-boundary resolution")
        return self.coarse_panel_step_N / factor

    def nodes(self, span_N: float, factor: int) -> int:
        intervals = span_N / self.panel_step(factor)
        rounded = round(intervals)
        if not math.isclose(intervals, rounded, rel_tol=0.0, abs_tol=1.0e-10):
            raise ValueError("continuation anchor is not grid-aligned")
        return int(rounded) + 1

    def validate(self) -> None:
        inherited = 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",
        ):
            if getattr(self, name) != getattr(inherited, name):
                raise ValueError(f"G32C numerical setting changed: {name}")
        if not (
            0.0
            < self.continuation_scan_start_N
            <= self.coarse_last_contractive_anchor_N
            < self.coarse_first_nonclosing_anchor_N
            <= self.consumed_domain_endpoint_N
            < self.prospective_heldout_evaluation_start_N
            < self.prospective_heldout_endpoint_N
        ):
            raise ValueError("branch audit and future heldout chronology invalid")
        if not math.isclose(
            self.coarse_first_nonclosing_anchor_N
            - self.coarse_last_contractive_anchor_N,
            self.coarse_panel_step_N,
            rel_tol=0.0,
            abs_tol=4.0e-18,
        ):
            raise ValueError("coarse diagnostic bracket must be exactly one panel")
        if tuple(sorted(self.continuation_anchor_N)) != self.continuation_anchor_N:
            raise ValueError("continuation anchors must be strictly ordered")
        if len(set(self.continuation_anchor_N)) != len(self.continuation_anchor_N):
            raise ValueError("continuation anchors must be unique")
        if self.continuation_anchor_N[-2:] != (
            self.coarse_last_contractive_anchor_N,
            self.coarse_first_nonclosing_anchor_N,
        ):
            raise ValueError("diagnostic bracket must terminate the anchor ladder")
        if self.resolution_factors != (1, 2, 4):
            raise ValueError("exact coarse/middle/fine factors required")
        for factor in self.resolution_factors:
            for anchor in self.continuation_anchor_N:
                if self.nodes(anchor, factor) < 17:
                    raise ValueError("bounded continuation grid required")


NONBLIND_DIAGNOSTIC_AUDIT: dict[str, Any] = {
    "G32C_bound_logH_recovery_pilot_attempts": 1,
    "G32C_bound_logH_recovery_completed_resolution_levels": 0,
    "G32C_bound_logH_recovery_report_written": False,
    "G32C_bound_logH_recovery_checkpoint_or_seed_released": False,
    "G32C_bound_logH_recovery_failure": (
        "log-H background integration failed: Required step size is less "
        "than spacing between numbers."
    ),
    "simple_branch_backtracking_full_pass": False,
    "simple_branch_backtracking_final_observed_residual": 0.5096109970992637,
    "portal_mass2_sign_change_bracket_N": [0.040703125, 0.04078125],
    "portal_mass2_minimum_Mpl2": -8.615236139676526e-9,
    "first_map_chi2_profile": [
        {"N": 0.08, "chi2_Mpl2": 4.742604466182654e-7},
        {"N": 0.085, "chi2_Mpl2": 3.857086433543367e-6},
        {"N": 0.09, "chi2_Mpl2": 3.2218257581379534e-5},
        {"N": 0.095, "chi2_Mpl2": 2.6316572331855614e-4},
        {"N": 0.10, "chi2_Mpl2": 2.01266010981336e-3},
    ],
    "last_reproduced_contractive_anchor": {
        "N": 0.09953125,
        "iteration_10_source_gross_relative_change": 1.8570549054570691e-10,
        "H_endpoint_Mpl": 1.5444790615694082e-7,
    },
    "first_nonclosing_one_panel_extension": {
        "N": 0.099609375,
        "iteration_1_source_gross_relative_change": 0.20222412465560607,
        "iteration_1_H_endpoint_Mpl": 4.6848455123610343e-8,
        "iteration_2_background_result": "NONPASS_required_step_below_spacing",
    },
    "nonblind_diagnostic_banks": 16,
    "background_integrations_including_failed_recovery_attempt": 171,
    "operator_source_assemblies": 125,
    "trajectory_rows_persisted": 0,
    "nonpass_artifacts_retained": 0,
    "physical_response_kernel_runs": 0,
}


def file_sha256(path: Path) -> str:
    digest = sha256()
    with path.open("rb") as stream:
        for block in iter(lambda: stream.read(1024 * 1024), b""):
            digest.update(block)
    return digest.hexdigest()


def _utc_now() -> str:
    return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")


def verify_authorities(root: Path) -> dict[str, Any]:
    observed = {name: file_sha256(root / name) for name in EXPECTED_AUTHORITIES}
    if observed != EXPECTED_AUTHORITIES:
        changed = [
            name
            for name, expected in EXPECTED_AUTHORITIES.items()
            if observed.get(name) != expected
        ]
        raise TachyonicBranchBoundaryPreflightError(
            f"G32C/recovery authority drift: {changed}"
        )
    if (root / FAILED_RECOVERY_OUTPUT).exists():
        raise TachyonicBranchBoundaryPreflightError(
            "failed recovery pilot report must not exist"
        )
    report = json.loads(
        (
            root
            / "AP1/APEIRON_AP1_M1_LOGH_POSITIVE_BRANCH_RECOVERY_PREFLIGHT_LATEST.json"
        ).read_text(encoding="utf-8")
    )
    if not report.get("all_preflight_gates_pass"):
        raise TachyonicBranchBoundaryPreflightError("G32C is not PASS")
    if report.get("prospective_heldout_eligible"):
        raise TachyonicBranchBoundaryPreflightError("future heldout is not locked")
    g32c.verify_authorities(root)
    return report


def physical_to_h2_state(state: np.ndarray, H_reference: float) -> np.ndarray:
    values = np.asarray(state, dtype=float)
    reference = float(H_reference)
    if values.shape != (5,) or not np.all(np.isfinite(values)):
        raise TachyonicBranchBoundaryPreflightError("finite five-component state required")
    if reference <= 0.0 or not math.isfinite(reference) or values[4] <= 0.0:
        raise TachyonicBranchBoundaryPreflightError("finite positive H chart required")
    transformed = values.copy()
    transformed[4] = (values[4] / reference) ** 2
    return transformed


def h2_to_physical_state(state: np.ndarray, H_reference: float) -> np.ndarray:
    values = np.asarray(state, dtype=float)
    reference = float(H_reference)
    if values.shape != (5,) or not np.all(np.isfinite(values)):
        raise TachyonicBranchBoundaryPreflightError("finite five-component H2 state required")
    if reference <= 0.0 or not math.isfinite(reference) or values[4] <= 0.0:
        raise TachyonicBranchBoundaryPreflightError("H2 chart requires u_H > 0")
    physical = values.copy()
    physical[4] = reference * math.sqrt(float(values[4]))
    if physical[4] <= 0.0 or not math.isfinite(float(physical[4])):
        raise TachyonicBranchBoundaryPreflightError("H2 reconstruction left branch")
    return physical


def direct_rhs_to_h2(
    physical_state: np.ndarray, direct_rhs: np.ndarray, H_reference: float
) -> np.ndarray:
    state = np.asarray(physical_state, dtype=float)
    derivative = np.asarray(direct_rhs, dtype=float)
    reference = float(H_reference)
    if state.shape != (5,) or derivative.shape != (5,):
        raise TachyonicBranchBoundaryPreflightError("five-component state and RHS required")
    if not np.all(np.isfinite(state)) or not np.all(np.isfinite(derivative)):
        raise TachyonicBranchBoundaryPreflightError("finite state and RHS required")
    if reference <= 0.0 or not math.isfinite(reference) or state[4] <= 0.0:
        raise TachyonicBranchBoundaryPreflightError("positive H reference required")
    transformed = derivative.copy()
    transformed[4] = 2.0 * state[4] * derivative[4] / reference**2
    return transformed


def h2_rhs_to_direct(
    physical_state: np.ndarray, h2_rhs: np.ndarray, H_reference: float
) -> np.ndarray:
    state = np.asarray(physical_state, dtype=float)
    derivative = np.asarray(h2_rhs, dtype=float)
    reference = float(H_reference)
    if state.shape != (5,) or derivative.shape != (5,):
        raise TachyonicBranchBoundaryPreflightError("five-component state and RHS required")
    if not np.all(np.isfinite(state)) or not np.all(np.isfinite(derivative)):
        raise TachyonicBranchBoundaryPreflightError("finite state and RHS required")
    if reference <= 0.0 or not math.isfinite(reference) or state[4] <= 0.0:
        raise TachyonicBranchBoundaryPreflightError("positive H reference required")
    recovered = derivative.copy()
    recovered[4] = derivative[4] * reference**2 / (2.0 * state[4])
    return recovered


def h2_equivalence_canary() -> dict[str, Any]:
    reference = 4.3e-7
    roundtrip: list[float] = []
    rhs_defects: list[float] = []
    positive: list[bool] = []
    for ratio in (2.0**-20, 0.25, 0.75, 1.0, 1.5, 4.0, 2.0**20):
        state = np.array([0.2, -3.0e-8, -0.4, 2.0e-8, reference * ratio])
        transformed = physical_to_h2_state(state, reference)
        restored = h2_to_physical_state(transformed, reference)
        roundtrip.append(
            abs(float(restored[4] - state[4]))
            / max(abs(float(state[4])), 1.0e-300)
        )
        positive.append(bool(restored[4] > 0.0 and math.isfinite(restored[4])))
        direct = np.array([1.0e-3, -2.0e-4, 3.0e-3, -4.0e-4, -5.0e-9])
        h2_rhs = direct_rhs_to_h2(state, direct, reference)
        recovered_rhs = h2_rhs_to_direct(state, h2_rhs, reference)
        rhs_defects.append(
            float(np.max(np.abs(recovered_rhs - direct)))
            / max(float(np.max(np.abs(direct))), 1.0e-300)
        )
    N = np.linspace(0.0, 0.12, 129)
    epsilon = 0.73
    u_H = np.exp(-2.0 * epsilon * N)
    reconstructed = reference * np.sqrt(u_H)
    analytic = reference * np.exp(-epsilon * N)
    toy_defect = float(
        np.max(np.abs(reconstructed - analytic))
        / max(float(np.max(np.abs(analytic))), 1.0e-300)
    )
    return {
        "chart": H2_CHART,
        "max_H_roundtrip_relative_defect": float(max(roundtrip)),
        "max_RHS_reconstruction_relative_defect": float(max(rhs_defects)),
        "positive_H_for_all_finite_positive_u_H_canaries": bool(all(positive)),
        "analytic_positive_H_toy_relative_defect": toy_defect,
        "canary_cap": CANARY_CAP,
    }


def plan_manifest(plan: BranchBoundaryPlan) -> dict[str, Any]:
    result = asdict(plan)
    result["continuation_anchor_N"] = list(plan.continuation_anchor_N)
    result["resolution_factors"] = list(plan.resolution_factors)
    result["node_counts_by_resolution"] = {
        str(factor): {
            format(anchor, ".9f"): plan.nodes(anchor, factor)
            for anchor in plan.continuation_anchor_N
        }
        for factor in plan.resolution_factors
    }
    result["positive_branch_charts"] = [g32c.LOGH_CHART, H2_CHART]
    result["pass_definition"] = {
        "all_lower_anchors": (
            "complete ten unchanged Picard steps with finite positive H and "
            "fixed-point source gross residual <= inherited 0.002 ceiling"
        ),
        "boundary_classification": (
            "independent log-H and H2 charts must agree on the last PASS / "
            "first NONPASS bracket to within one grid panel at each resolution"
        ),
        "resolution_requirement": (
            "coarse/middle/fine boundary brackets finite and non-expanding"
        ),
        "persistence": "aggregate full-PASS branch audit only; zero trajectories",
    }
    return result


def build_preflight(root: Path) -> dict[str, Any]:
    authority = verify_authorities(root)
    plan = BranchBoundaryPlan()
    plan.validate()
    canary = h2_equivalence_canary()
    profile = NONBLIND_DIAGNOSTIC_AUDIT["first_map_chi2_profile"]
    chi2_values = [float(item["chi2_Mpl2"]) for item in profile]
    inherited_ceiling = float(
        g32.PREDECLARED_POLICY["inherited_metric_freeze_policy"]
        ["max_fixed_point_source_gross_relative_change"]["ceiling"]
    )
    lower = NONBLIND_DIAGNOSTIC_AUDIT["last_reproduced_contractive_anchor"]
    upper = NONBLIND_DIAGNOSTIC_AUDIT["first_nonclosing_one_panel_extension"]
    gates = {
        "G32C_authorities_hash_bound_and_PASS": True,
        "failed_logH_recovery_output_absent": True,
        "failed_logH_recovery_attempt_not_checkpointed_or_seeded": bool(
            not NONBLIND_DIAGNOSTIC_AUDIT[
                "G32C_bound_logH_recovery_report_written"
            ]
            and not NONBLIND_DIAGNOSTIC_AUDIT[
                "G32C_bound_logH_recovery_checkpoint_or_seed_released"
            ]
        ),
        "consumed_domain_used_only_for_nonblind_diagnostics": bool(
            plan.continuation_anchor_N[-1] <= plan.consumed_domain_endpoint_N
        ),
        "prospective_heldout_strictly_beyond_consumed_domain_and_locked": bool(
            plan.prospective_heldout_evaluation_start_N
            > plan.consumed_domain_endpoint_N
            and not authority["prospective_heldout_eligible"]
        ),
        "coarse_observed_boundary_bracket_is_one_registered_panel": bool(
            math.isclose(
                float(upper["N"]) - float(lower["N"]),
                plan.coarse_panel_step_N,
                rel_tol=0.0,
                abs_tol=4.0e-18,
            )
        ),
        "last_observed_lower_anchor_below_inherited_source_ceiling": bool(
            float(lower["iteration_10_source_gross_relative_change"])
            <= inherited_ceiling
        ),
        "first_observed_upper_anchor_is_explicit_NONPASS": bool(
            upper["iteration_2_background_result"].startswith("NONPASS")
        ),
        "observed_chi2_profile_is_finite_positive_and_strictly_increasing": bool(
            all(math.isfinite(value) and value > 0.0 for value in chi2_values)
            and all(right > left for left, right in zip(chi2_values, chi2_values[1:]))
        ),
        "H2_roundtrip_below_machine_canary_cap": bool(
            canary["max_H_roundtrip_relative_defect"] <= CANARY_CAP
        ),
        "H2_RHS_reconstruction_below_machine_canary_cap": bool(
            canary["max_RHS_reconstruction_relative_defect"] <= CANARY_CAP
        ),
        "H2_analytic_positive_branch_toy_below_machine_canary_cap": bool(
            canary["analytic_positive_H_toy_relative_defect"] <= CANARY_CAP
        ),
        "H2_canaries_reconstruct_only_positive_H": bool(
            canary["positive_H_for_all_finite_positive_u_H_canaries"]
        ),
        "H2_reference_is_algebraically_independent_of_logH_chart": bool(
            H2_CHART != g32c.LOGH_CHART
        ),
        "three_exact_nested_resolution_factors_registered": bool(
            plan.resolution_factors == (1, 2, 4)
        ),
        "all_continuation_anchors_align_on_all_registered_grids": bool(
            all(
                plan.nodes(anchor, factor) >= 17
                for factor in plan.resolution_factors
                for anchor in plan.continuation_anchor_N
            )
        ),
        "equations_physics_parameters_counterterms_PV_split_and_modes_unchanged": True,
        "fixed_point_count_relaxation_and_existing_gate_ceilings_unchanged": True,
        "preflight_runs_zero_backgrounds_and_zero_response_kernels": True,
        "no_trajectory_seed_curve_fit_or_significance": True,
    }
    passed = bool(all(gates.values()))
    self_authorities = {
        "AP1/CODE/ap1_m1_tachyonic_branch_boundary_preflight.py": file_sha256(
            Path(__file__).resolve()
        ),
        "AP1/CODE/test_ap1_m1_tachyonic_branch_boundary_preflight.py": file_sha256(
            root
            / "AP1/CODE/test_ap1_m1_tachyonic_branch_boundary_preflight.py"
        ),
    }
    return {
        "schema": "apeiron-ap1-m1-tachyonic-branch-boundary-preflight-v1.0",
        "updated_utc": _utc_now(),
        "classification": (
            "M1_TACHYONIC_BRANCH_BOUNDARY_PREFLIGHT_PASS_G32D_MULTIRESOLUTION_EXISTENCE_AUDIT_OPEN_NEW_HELDOUT_LOCKED_PHYSICAL_KERNEL_BLOCKED"
            if passed
            else "M1_TACHYONIC_BRANCH_BOUNDARY_PREFLIGHT_NONPASS"
        ),
        "authority_sha256": {**EXPECTED_AUTHORITIES, **self_authorities},
        "failed_recovery_output_required_absent": FAILED_RECOVERY_OUTPUT,
        "nonblind_diagnostic_audit": NONBLIND_DIAGNOSTIC_AUDIT,
        "branch_boundary_plan": plan_manifest(plan),
        "H2_equivalence_canary": canary,
        "gates": gates,
        "all_preflight_gates_pass": passed,
        "background_runs": 0,
        "physical_response_kernel_runs": 0,
        "branch_boundary_pilot_eligible": passed,
        "prospective_heldout_eligible": False,
        "checkpoint_eligible": passed,
        "seed_released": False,
        "nonpass_stored_or_used_as_seed": False,
        "equations_changed": False,
        "physics_changed": False,
        "parameters_changed": False,
        "existing_gate_thresholds_changed": False,
        "AP1_status": "ORANGE",
        "claim_boundary": (
            "structural and chronology preflight plus explicitly non-blind "
            "single-resolution diagnostic bracket only; not a converged "
            "multiresolution branch boundary, production background, present "
            "anchor, response kernel, observable, curve, fit, or significance"
        ),
        "next_required": (
            "run the registered log-H/H2 multiresolution branch-existence "
            "audit within consumed N<=0.10 and persist only its complete PASS; "
            "do not evaluate N=0.105..0.12"
            if passed
            else "stop fail-closed; do not run or persist the boundary audit"
        ),
    }


def checkpoint_markdown(report: dict[str, Any]) -> str:
    audit = report["nonblind_diagnostic_audit"]
    lower = audit["last_reproduced_contractive_anchor"]
    upper = audit["first_nonclosing_one_panel_extension"]
    return f"""# Apeiron AP1 – G32D tachyonic branch-boundary preflight

**Updated UTC:** {report['updated_utc']}  
**Classification:** `{report['classification']}`  
**AP1 status:** ORANGE

The G32C-bound log-H recovery pilot stopped before completing its coarse
level.  No pilot report, checkpoint, trajectory, or seed was written.  All
subsequent diagnostics used only the already consumed N<=0.10 domain.

The first-map growth is localized to the tachyonic chi2 channel.  A
paneled non-blind continuation reproduced a contractive positive-H anchor at
N={lower['N']} with source residual
{lower['iteration_10_source_gross_relative_change']:.17g} and H=
{lower['H_endpoint_Mpl']:.17g} Mpl.  The next coarse panel at N={upper['N']}
reached H={upper['iteration_1_H_endpoint_Mpl']:.17g} Mpl on its first
iteration and then stopped fail-closed on the second background integration.
This is a single-resolution diagnostic bracket, not yet a physical branch
termination claim.

G32D predeclares a coarse/middle/fine branch-existence audit using both the
log-H chart and the algebraically independent
`{H2_CHART}` chart.  All {len(report['gates'])} structural gates pass.  The
preflight itself ran zero backgrounds and zero response kernels.

Equations, physics, parameters, counterterms, PV sectors, moving split, mode
transport, ten Picard steps, relaxation 0.9, and all existing gate ceilings
remain unchanged.  The prospective N=0.105..0.12 heldout, production
background, present anchor, physical response kernel, AP2/AP3, curves, fits,
and significances remain locked.
"""


def _write_pass_json(report: dict[str, Any], output: Path) -> None:
    if not report.get("all_preflight_gates_pass"):
        raise TachyonicBranchBoundaryPreflightError("NONPASS report was not written")
    serialized = json.dumps(report, indent=2, allow_nan=False) + "\n"
    output.parent.mkdir(parents=True, exist_ok=True)
    with output.open("x", encoding="utf-8") as stream:
        stream.write(serialized)


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("apeiron_root", type=Path)
    parser.add_argument("--json-output", type=Path, required=True)
    parser.add_argument("--md-output", type=Path, required=True)
    args = parser.parse_args()
    report = build_preflight(args.apeiron_root)
    if args.json_output.exists() or args.md_output.exists():
        raise FileExistsError("preflight output already exists")
    _write_pass_json(report, args.json_output)
    with args.md_output.open("x", encoding="utf-8") as stream:
        stream.write(checkpoint_markdown(report))


if __name__ == "__main__":
    main()
