"""G32A fail-closed precision semantics for the balanced coupled M1 pilot.

This is a structural and numerical-contract preflight only.  It changes no
Apeiron/AME-1 v7.13 or M-1 equation, physical parameter, counterterm,
Pauli--Villars sector, moving split, numerical operator setting, or existing
gate threshold.  It makes two previously implicit distinctions explicit:

* a Richardson order is required when a three-level delta is resolved above
  the already registered metric floor; below that floor, finite monotonicity
  remains mandatory but the order is classified as unidentifiable;
* G31 proves that the R/Q transport can cross its registered pole.  A coupled
  run must use that exact transport and pass all quality gates, but it need not
  encounter a pole on every particular trajectory.

The rejected developmental G32 pilot is not an input, is not serialized, and
is not used as a seed.  A retry must recompute all three pilot levels.
"""
from __future__ import annotations

import argparse
from datetime import datetime, timezone
from hashlib import sha256
import json
import math
from pathlib import Path
from typing import Any, Iterable

import ap1_m1_balanced_chart_transport as g31
import ap1_m1_balanced_coupled_stage_preflight as g32


EXPECTED_G32_AUTHORITIES = {
    "AP1/APEIRON_AP1_M1_BALANCED_COUPLED_STAGE_PREFLIGHT_LATEST.json": (
        "5e544bfbe4803fe8668285a80267549ee5d0f3516d6db2ce03f548ed2d0f3333"
    ),
    "AP1/APEIRON_AP1_M1_BALANCED_COUPLED_STAGE_PREFLIGHT_CHECKPOINT_LATEST.md": (
        "d009955b1a6c40dd07c413d468925f05967141a3f59a89f95141f855ea9e9ef0"
    ),
    "AP1/CODE/ap1_m1_balanced_coupled_stage_preflight.py": (
        "a2e1c19db0d18c05c38e62254bbe4dc1ef4d9b6488f11e3bcc15640bd3a71da2"
    ),
    "AP1/CODE/test_ap1_m1_balanced_coupled_stage_preflight.py": (
        "475f3f89043de4aba8f0c2dde041c7425cbfb9c917579f8f546c321016cca833"
    ),
}

TRANSPORT_METHOD = (
    "dimensionless_pivoted_R_Q_charts_with_determinant_one_RK4_transfer"
)


class BalancedCoupledPrecisionPreflightError(RuntimeError):
    """An authority, numerical-contract, chronology, or lock gate failed."""


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_g32_authorities(root: Path) -> tuple[dict[str, Any], dict[str, Any]]:
    observed = {
        name: file_sha256(root / name) for name in EXPECTED_G32_AUTHORITIES
    }
    if observed != EXPECTED_G32_AUTHORITIES:
        changed = [
            name
            for name, expected in EXPECTED_G32_AUTHORITIES.items()
            if observed.get(name) != expected
        ]
        raise BalancedCoupledPrecisionPreflightError(
            f"G32 authority drift: {changed}"
        )
    report = json.loads(
        (
            root
            / "AP1/APEIRON_AP1_M1_BALANCED_COUPLED_STAGE_PREFLIGHT_LATEST.json"
        ).read_text(encoding="utf-8")
    )
    if not report.get("all_preflight_gates_pass") or not report.get(
        "checkpoint_eligible"
    ):
        raise BalancedCoupledPrecisionPreflightError("G32 preflight is not PASS")
    if report.get("predeclared_policy") != g32.PREDECLARED_POLICY:
        raise BalancedCoupledPrecisionPreflightError(
            "G32 policy differs from its hash-bound implementation"
        )
    _, g31_checkpoint = g32.verify_authorities(root)
    return report, g31_checkpoint


def component_resolution_floor(metric_name: str) -> float:
    """Return the existing, unchanged floor for a component delta family."""

    policy = g32.PREDECLARED_POLICY["inherited_metric_freeze_policy"]
    if metric_name.startswith("background."):
        return float(policy["max_background_time_relative_delta"]["floor"])
    if metric_name.startswith("source."):
        return float(policy["max_source_time_gross_relative_delta"]["floor"])
    raise BalancedCoupledPrecisionPreflightError(
        f"unregistered three-level metric family: {metric_name}"
    )


def assess_richardson_pair(
    metric_name: str,
    coarse_to_middle_delta: float,
    middle_to_fine_delta: float,
    minimum_order: float,
) -> dict[str, Any]:
    """Apply finite monotonicity and a floor-aware Richardson-order gate."""

    coarse = float(coarse_to_middle_delta)
    fine = float(middle_to_fine_delta)
    floor = component_resolution_floor(metric_name)
    finite_nonnegative = bool(
        math.isfinite(coarse)
        and math.isfinite(fine)
        and coarse >= 0.0
        and fine >= 0.0
    )
    monotone = bool(finite_nonnegative and fine <= coarse)
    below_floor = bool(
        finite_nonnegative and coarse <= floor and fine <= floor
    )
    if not finite_nonnegative:
        ratio = None
        order = None
    elif coarse == 0.0:
        ratio = 0.0 if fine == 0.0 else None
        order = None
    elif fine == 0.0:
        ratio = 0.0
        order = None
    else:
        ratio = fine / coarse
        order = math.log(coarse / fine, 2.0)

    if below_floor:
        order_gate_pass = monotone
        basis = "finite_monotone_below_inherited_resolution_floor"
    else:
        order_gate_pass = bool(
            monotone and order is not None and order >= float(minimum_order)
        )
        basis = "observed_Richardson_order_at_or_above_resolution_floor"
    return {
        "coarse_to_middle_delta": coarse if math.isfinite(coarse) else None,
        "middle_to_fine_delta": fine if math.isfinite(fine) else None,
        "fine_over_coarse_delta_ratio": ratio,
        "observed_Richardson_order": order,
        "resolution_floor": floor,
        "both_deltas_below_resolution_floor": below_floor,
        "finite_nonnegative": finite_nonnegative,
        "monotone": monotone,
        "minimum_order_pass": order_gate_pass,
        "order_gate_basis": basis,
    }


def exact_transport_used(diagnostics: Iterable[dict[str, Any]]) -> bool:
    """Require the G31 implementation, independent of switch occurrence."""

    items = list(diagnostics)
    return bool(
        items
        and all(item.get("transport_method") == TRANSPORT_METHOD for item in items)
    )


def build_preflight(root: Path, code_path: Path, test_path: Path) -> dict[str, Any]:
    g32_report, g31_checkpoint = verify_g32_authorities(root)
    policy = g32_report["predeclared_policy"]
    inherited = policy["inherited_metric_freeze_policy"]
    background_floor = component_resolution_floor("background.maximum")
    source_floor = component_resolution_floor("source.maximum")
    minimum_order = float(policy["minimum_observed_Richardson_order"])
    fine_chart = g31_checkpoint["metrics"]["fine_balanced_diagnostics"]
    gates = {
        "G32_authority_chain_hash_exact_and_PASS": True,
        "G31_pole_crossing_capability_remains_hash_bound": bool(
            g32_report["gates"]["G31_balanced_chart_reference_PASS"]
            and fine_chart["dynamic_chart_switches"] > 0
            and fine_chart["vacuum_resets"] == 0
            and fine_chart["transport_method"] == TRANSPORT_METHOD
        ),
        "existing_background_resolution_floor_retained_exactly": bool(
            background_floor
            == float(inherited["max_background_time_relative_delta"]["floor"])
            == 1.0e-10
        ),
        "existing_source_resolution_floor_retained_exactly": bool(
            source_floor
            == float(inherited["max_source_time_gross_relative_delta"]["floor"])
            == 1.0e-9
        ),
        "minimum_Richardson_order_retained_exactly": bool(
            minimum_order == 0.5
        ),
        "finite_monotonicity_required_at_every_scale": True,
        "order_required_only_when_numerically_identifiable": True,
        "runtime_chart_switch_occurrence_not_confused_with_transport_capability": True,
        "exact_G31_transport_and_all_quality_gates_remain_required": True,
        "pilot_retry_recomputes_all_three_levels_without_seed": True,
        "equations_physics_parameters_and_existing_thresholds_unchanged": True,
        "no_background_kernel_trajectory_seed_curve_fit_or_significance": True,
    }
    passed = bool(all(gates.values()))
    return {
        "schema": "apeiron-ap1-m1-balanced-coupled-precision-preflight-v1.0",
        "updated_utc": _utc_now(),
        "classification": (
            "M1_BALANCED_COUPLED_PRECISION_AWARE_ORDER_PREFLIGHT_PASS_PILOT_RETRY_OPEN_PHYSICAL_KERNEL_BLOCKED"
            if passed
            else "M1_BALANCED_COUPLED_PRECISION_AWARE_ORDER_PREFLIGHT_NONPASS"
        ),
        "authority_sha256": {
            **EXPECTED_G32_AUTHORITIES,
            "AP1/CODE/ap1_m1_balanced_coupled_precision_preflight.py": file_sha256(
                code_path
            ),
            "AP1/CODE/test_ap1_m1_balanced_coupled_precision_preflight.py": file_sha256(
                test_path
            ),
        },
        "precision_policy": {
            "minimum_observed_Richardson_order": minimum_order,
            "background_component_resolution_floor": background_floor,
            "source_component_resolution_floor": source_floor,
            "finite_monotonicity_required_for_every_component": True,
            "below_floor_rule": (
                "when both nested deltas are at or below the inherited family "
                "floor, require finite monotonicity and classify order as "
                "unidentifiable below the registered resolution floor"
            ),
            "at_or_above_floor_rule": (
                "require finite monotonicity and observed Richardson order >= 0.5"
            ),
            "floors_are_reused_resolution_classifiers_not_new_tolerances": True,
        },
        "chart_transport_policy": {
            "required_transport_method": TRANSPORT_METHOD,
            "pole_crossing_capability_authority": (
                "G31 balanced-chart reference checkpoint"
            ),
            "dynamic_switch_required_in_every_runtime_trajectory": False,
            "vacuum_resets_allowed": 0,
            "active_ratio_cap": float(g31.REFERENCE_POLICY["active_ratio_cap"]),
            "wronskian_relative_cap": float(
                g31.REFERENCE_POLICY["wronskian_relative_cap"]
            ),
            "transfer_determinant_defect_cap": float(
                g31.REFERENCE_POLICY["transfer_determinant_defect_cap"]
            ),
        },
        "developmental_attempt_audit": {
            "discarded_G32_pilot_attempts": 1,
            "discarded_attempt_background_resolution_runs": 3,
            "discarded_attempt_report_written": False,
            "discarded_attempt_used_as_seed": False,
            "discarded_attempt_metrics_reused": False,
            "contract_revision_is_data_informed": True,
            "pilot_retry_must_recompute_all_three_levels": True,
            "future_disjoint_heldout_remains_unseen": True,
        },
        "gates": gates,
        "all_preflight_gates_pass": passed,
        "checkpoint_eligible": passed,
        "pilot_retry_eligible": passed,
        "background_runs": 0,
        "physical_response_kernel_runs": 0,
        "trajectory_rows_persisted": 0,
        "seed_released": False,
        "production_background_tolerances_frozen": 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": (
            "precision and chart-transport contract preflight only; no accepted "
            "pilot, tolerance freeze, heldout, production background, present "
            "anchor, response kernel, observable, curve, fit or significance"
        ),
        "next_required": (
            "rerun all three known-domain G32 pilot levels from scratch under "
            "this hash-bound G32A contract; persist only a complete PASS"
            if passed
            else "stop fail-closed; do not rerun, persist, checkpoint, freeze or seed"
        ),
    }


def checkpoint_markdown(report: dict[str, Any]) -> str:
    precision = report["precision_policy"]
    chart = report["chart_transport_policy"]
    attempt = report["developmental_attempt_audit"]
    return f"""# Apeiron AP1 – G32A precision-aware convergence preflight

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

G32A keeps the G32 equations, physics, parameters, numerical operator settings,
counterterms, and every registered threshold unchanged.  It closes two gate-
semantics ambiguities before any pilot retry.

## Frozen interpretation

- Minimum observable Richardson order remains `{precision['minimum_observed_Richardson_order']}`.
- Background component floor remains `{precision['background_component_resolution_floor']}`.
- Source component floor remains `{precision['source_component_resolution_floor']}`.
- Finite monotonicity is mandatory at every scale.
- If both nested differences are below their inherited family floor, the order
  is not numerically identifiable; monotonicity remains the pass condition.
- At or above the floor, the unchanged Richardson-order gate is mandatory.
- Runtime transport must be exactly
  `{chart['required_transport_method']}` and retain every G31 quality gate.
- G31 remains the hash-bound proof of pole-crossing capability.  A dynamic chart
  switch is not forced when a particular coupled trajectory never reaches the pole.

## Fail-closed audit

The prior developmental attempt used
`{attempt['discarded_attempt_background_resolution_runs']}` background-resolution
runs, produced no stored pilot report, and supplied no seed or metric input.
This revision is explicitly data-informed.  Therefore the retry must recompute
all three pilot levels from scratch, while the registered disjoint heldout remains
unseen.

## Boundary

This is a structural numerical-contract PASS only.  It is not an accepted
background pilot or production background.  No tolerance is frozen, no
trajectory or seed is released, and the physical two-time response kernel,
present anchor, AP2/AP3, curves, fits, observables, and significances remain
locked.
"""


def write_pass_preflight(
    report: dict[str, Any], output: Path, checkpoint: Path
) -> None:
    if not report.get("all_preflight_gates_pass"):
        raise BalancedCoupledPrecisionPreflightError(
            "NONPASS precision preflight was not written"
        )
    if output.exists() or checkpoint.exists():
        raise FileExistsError("precision preflight output already exists")
    output.parent.mkdir(parents=True, exist_ok=True)
    checkpoint.parent.mkdir(parents=True, exist_ok=True)
    with output.open("x", encoding="utf-8") as stream:
        stream.write(json.dumps(report, indent=2, allow_nan=False) + "\n")
    with checkpoint.open("x", encoding="utf-8") as stream:
        stream.write(checkpoint_markdown(report))


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("apeiron_root", type=Path)
    parser.add_argument("--test-path", type=Path, required=True)
    parser.add_argument("--output", type=Path, required=True)
    parser.add_argument("--checkpoint", type=Path, required=True)
    args = parser.parse_args()
    report = build_preflight(
        args.apeiron_root, Path(__file__).resolve(), args.test_path
    )
    write_pass_preflight(report, args.output, args.checkpoint)


if __name__ == "__main__":
    main()
