"""Lexicographic fixed-H Q_rho minimax from a validated low-Ward p65 PASS."""
from __future__ import annotations

import argparse
import json
from pathlib import Path

import numpy as np

from ap1_r2c_implicit_dae_multiresolution import _physical_diagnostics
from ap1_r2c_implicit_dae_solver import ImplicitDAEResidual
from p42_fixed_h_minimax import solve_fixed_h_minimax


ROOT = Path(__file__).resolve().parent
if not (ROOT / "Apeiron").is_dir():
    ROOT = ROOT.parents[2]
STATE = ROOT / "Apeiron/HANDOFF/CURRENT_STATE_LATEST.npz"
SOURCE = ROOT / "Apeiron/AP1/APEIRON_AP1_R2C_P65_MONOTONIC_CANDIDATE_LATEST.json"
AUDIT = ROOT / "Apeiron/AP1/APEIRON_AP1_R2C_G22_17_33_65_AUDIT_LATEST.json"
P33_BANK = ROOT / "Apeiron/AP1/APEIRON_AP1_R2C_P33_MONOTONIC_MINIMAX_DIAGNOSTIC_LATEST.json"


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--output", type=Path, required=True)
    args = parser.parse_args()

    source = json.loads(SOURCE.read_text(encoding="utf-8"))
    if not source.get("accepted_as_checkpoint"):
        raise RuntimeError("validated low-Ward p65 PASS required")
    baseline = np.asarray(source["solution_vector"], dtype=float)
    audit = json.loads(AUDIT.read_text(encoding="utf-8"))
    p17 = next(level for level in audit["levels"] if level["candidate_nodes"] == 17)
    caps = p17["diagnostics"]
    system = ImplicitDAEResidual(STATE, nodes=65, uv_homotopy=1.0)
    result, _selected = solve_fixed_h_minimax(
        system,
        baseline,
        radii=(1.0e-8, 3.0e-8, 1.0e-7, 3.0e-7, 1.0e-6, 3.0e-6, 1.0e-5),
        full_radius_diagnostics=True,
        objective_mode="rho_lexicographic",
        background_residual_cap=8.0e-5,
    )
    eligible = []
    compact = []
    for item in result["full_radius_diagnostics"]:
        diagnostics = item["full_diagnostics"]
        below_caps = {
            "ward_normalized": diagnostics["ward_normalized"]
            <= caps["ward_normalized"],
            "validation_source_relative_change": diagnostics[
                "validation_source_relative_change"
            ] <= caps["validation_source_relative_change"],
        }
        compact.append({
            "trust_radius": item["trust_radius"],
            "predicted_rho_minimax": item["predicted_minimax"],
            "verified_background_max_abs": item[
                "verified_background_max_abs"
            ],
            "verified_rho_closure_max_abs": item[
                "verified_rho_closure_max_abs"
            ],
            "full_diagnostics": diagnostics,
            "all_absolute_gates_pass": item["all_absolute_gates_pass"],
            "below_p17_caps": below_caps,
        })
        if item["all_absolute_gates_pass"] and all(below_caps.values()):
            eligible.append((
                item["verified_rho_closure_max_abs"],
                np.asarray(item["solution_vector"], dtype=float),
                compact[-1],
            ))
    p33_bank = json.loads(P33_BANK.read_text(encoding="utf-8"))
    p33_candidates = [
        item["full_diagnostics"]
        for item in p33_bank.get("full_radius_diagnostics", [])
        if item.get("all_absolute_gates_pass")
    ]
    compatible = []
    for row in eligible:
        diagnostics = row[2]["full_diagnostics"]
        bridges = [
            item for item in p33_candidates
            if diagnostics["ward_normalized"] <= item["ward_normalized"]
            <= caps["ward_normalized"]
            and diagnostics["validation_source_relative_change"]
            <= item["validation_source_relative_change"]
            <= caps["validation_source_relative_change"]
        ]
        if bridges:
            row[2]["compatible_p33_candidates"] = len(bridges)
            compatible.append(row)
    selected = min(
        compatible,
        key=lambda row: row[2]["full_diagnostics"]["ward_normalized"],
    ) if compatible else None
    repeats = []
    if selected:
        repeats = [_physical_diagnostics(system, selected[1]) for _ in range(3)]
    payload = {
        "schema": "apeiron-ap1-r2c-p65-rho-lexicographic-minimax-v1.0",
        "source": "validated_low_Ward_p65_PASS_only",
        "method": "fixed_H_velocity_minimax_with_background_cap_and_Q_rho_objective",
        "background_residual_cap": 8.0e-5,
        "radius_scan": compact,
        "eligible_count": len(eligible),
        "compatible_chain_candidate_count": len(compatible),
        "selected": selected[2] if selected else None,
        "repeated_full_diagnostics": repeats,
        "all_repeats_identical": bool(
            repeats and all(item == repeats[0] for item in repeats[1:])
        ),
        "accepted_as_checkpoint": selected is not None,
        "solution_vector": selected[1].tolist() if selected else None,
        "trial_vectors_stored_or_used_as_seed": False,
        "equations_changed": False,
        "physics_changed": False,
        "gates_changed": False,
        "production_curves_released": False,
    }
    args.output.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")


if __name__ == "__main__":
    main()
