#!/usr/bin/env python3
"""
verify_P074.py -- Addendum 74: theta13 PMNS closure.

The paper contains several abandoned intermediate mechanisms.  This verifier
checks the durable claims: the A68 NLO value, the abstract/final P74 formula,
the fitted delta_QLC route, and the final PMNS status table.
"""

import math
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))

PASS = FAIL = 0
_N = 0


def check(n, desc, cond):
    global PASS, FAIL
    ok = bool(cond)
    PASS += ok
    FAIL += not ok
    print(f"  [{'PASS' if ok else 'FAIL'}] {n:>2}. {desc}")
    return ok


class Verifier:
    """Output adapter: identical check semantics, modern [PASS]/[FAIL] format."""

    def __init__(self, name):
        print(name)

    def check(self, label, computed, claimed, *, rel=1e-3, abs_tol=None, detail=""):
        if abs_tol is not None:
            ok = abs(computed - claimed) <= abs_tol
            err_detail = f"abs err={abs(computed - claimed):.6g}, tol={abs_tol:.6g}"
        else:
            if claimed == 0:
                ok = abs(computed) <= (rel or 1e-12)
                err_detail = f"abs value={abs(computed):.6g}, tol={rel:.6g}"
            else:
                err = (computed - claimed) / abs(claimed)
                ok = abs(err) <= (rel or 0)
                err_detail = f"rel err={100 * err:+.6g}%, tol={100 * (rel or 0):.6g}%"
        return self.record(label, ok, computed, claimed, detail, err_detail)

    def record(self, label, ok, computed="", claimed="", detail="", err_detail=""):
        global _N
        _N += 1
        desc = label + (f" -- {detail}" if detail else "")
        check(_N, desc, ok)
        if computed != "" or claimed != "":
            print(f"        computed: {computed}")
            print(f"        claimed : {claimed}")
        if err_detail:
            print(f"        {err_detail}")
        return ok

    def summary(self):
        print(f"\n{'='*60}\nRESULT: {PASS} PASS / {FAIL} FAIL")
        return 1 if FAIL else 0


v = Verifier("P074 -- Reactor Angle theta13 Closure")

ROOT = Path(__file__).resolve().parents[1]
TEX = (ROOT / "74_Addendum_Theta13Closure.tex").read_text()

PI = math.pi
LAM = math.sin(PI / 14)
PDG_SIN13 = 0.14988
PDG_THETA13 = 8.620
SIGMA_THETA13 = 0.130


def angle_from_sin(value: float) -> float:
    return math.degrees(math.asin(value))


def residual(value: float, target: float) -> float:
    return 100 * (value - target) / target


lo_sin = LAM / math.sqrt(2)
lo_angle = angle_from_sin(lo_sin)
nlo_sin = lo_sin * (1 - LAM**2 / 4)
nlo_angle = angle_from_sin(nlo_sin)

v.check("lambda = sin(pi/14)", LAM, 0.22252, rel=5e-6)
v.check("LO sin theta13 = lambda/sqrt(2)", lo_sin, 0.15732, rel=2e-4)
v.check("LO theta13", lo_angle, 9.05, rel=5e-4)
v.check("NLO sin theta13", nlo_sin, 0.15537, rel=2e-4)
v.check("NLO theta13", nlo_angle, 8.934, rel=8e-4)
v.check("NLO sin residual", nlo_sin - PDG_SIN13, 0.00549, rel=1e-2)
v.check("NLO relative residual vs NLO sin", 100 * (nlo_sin - PDG_SIN13) / nlo_sin, 3.53, rel=1e-2)
v.check("lambda^2/(8 sqrt2)", LAM**2 / (8 * math.sqrt(2)), 0.004376, rel=2e-4)

abstract_formula = lo_sin * (1 - LAM**2 / 4 - LAM**2 / (8 * math.sqrt(2)))
v.check(
    "abstract structural formula sin theta13",
    abstract_formula,
    0.15003,
    rel=5e-4,
    detail="Expected fail: the formula as printed gives about 0.15471, not 0.15003.",
)
v.check(
    "abstract structural formula theta13",
    angle_from_sin(abstract_formula),
    8.627,
    rel=5e-4,
    detail="Expected fail: the printed formula gives about 8.90 degrees.",
)

y2 = math.sin(2 * PI / 14)
delta_z = y2**2 / 4
wf_first_order = nlo_sin * (1 - delta_z / 2)
v.check("y2 = sin(2pi/14)", y2, 0.43388, rel=1e-5)
v.check("y2^2/4", delta_z, 0.047063, rel=2e-5)
v.check("wavefunction corrected sin", wf_first_order, 0.15172, rel=2e-4)
v.check("wavefunction corrected theta", angle_from_sin(wf_first_order), 8.722, rel=1e-3)

theta23_ckm_deg = 2.335
qlc_amp = -nlo_sin * (theta23_ckm_deg / 45) * (LAM / 2)
v.check("QLC back-reaction amplitude", qlc_amp, -0.000897, rel=2e-3)
v.check("theta after wavefunction plus QLC amplitude", angle_from_sin(wf_first_order + qlc_amp), 8.670, rel=1e-3)

def_sin = lo_sin * (1 - 3 * LAM**2 / 4)
def_angle = angle_from_sin(def_sin)
v.check("definitive pre-QLC sin", def_sin, 0.15148, rel=2e-4)
v.check("definitive pre-QLC theta", def_angle, 8.712, rel=5e-4)

qlc_degree_formula = -theta23_ckm_deg * LAM / ((PI / 4) * math.sqrt(2))
v.check(
    "QLC degree correction formula",
    qlc_degree_formula,
    -0.0817,
    rel=2e-2,
    detail="Expected fail: the displayed degree formula gives about -0.468 degrees; the paper then effectively multiplies by lambda again.",
)
v.check(
    "theta after displayed degree correction",
    def_angle + qlc_degree_formula,
    8.630,
    rel=5e-4,
    detail="Expected fail: using the displayed degree formula gives about 8.25 degrees.",
)

sin_delta_small = def_sin - 0.000145
sin_delta_fit = def_sin - 0.00147
angle_delta_small = angle_from_sin(sin_delta_small)
angle_delta_fit = angle_from_sin(sin_delta_fit)
v.check("small delta_QLC route sin", sin_delta_small, 0.15134, rel=2e-4)
v.check("small delta_QLC route theta", angle_delta_small, 8.703, rel=5e-4)
v.check("fitted delta_QLC route sin", sin_delta_fit, 0.15001, rel=2e-4)
v.check("fitted delta_QLC route theta", angle_delta_fit, 8.627, rel=5e-4)
v.check("fitted route residual degrees", angle_delta_fit - PDG_THETA13, 0.007, abs_tol=0.003)
v.check("fitted route sigma", (angle_delta_fit - PDG_THETA13) / SIGMA_THETA13, 0.05, rel=5e-1)
v.check(
    "abstract sigma for 0.007 degree residual",
    0.007 / SIGMA_THETA13,
    0.5,
    rel=2e-1,
    detail="Expected fail: 0.007 degrees is about 0.05 sigma for sigma=0.130 degrees, not 0.5 sigma.",
)

v.record(
    "abstract reference label exists",
    "\\label{cor:theta13-nnlo-value}" in TEX,
    "missing" if "\\label{cor:theta13-nnlo-value}" not in TEX else "present",
    "cor:theta13-nnlo-value",
    "Expected fail: the abstract references a corollary label that is not defined in this TeX file.",
)
v.record(
    "Phase 5d status is internally consistent",
    not ("therefore \\emph{incomplete}" in TEX and "Phase~5d for all PMNS parameters is closed" in TEX),
    "abstract says incomplete; later summary says closed",
    "single status",
    "Expected fail: the paper simultaneously flags delta_QLC as open/fitted and declares Phase 5d complete.",
)

theta12_pred, theta12_pdg = 33.38, 33.44
theta23_pred, theta23_pdg = 41.245, 42.20
delta_pred, delta_pdg = -66.43, -67.0
v.check(
    "PMNS table theta12 residual sign",
    theta12_pred - theta12_pdg,
    0.06,
    abs_tol=0.01,
    detail="Expected fail: TOE - PDG is -0.06 degrees, not +0.06.",
)
v.check(
    "PMNS table theta23 residual sign",
    theta23_pred - theta23_pdg,
    0.96,
    abs_tol=0.02,
    detail="Expected fail: TOE - PDG is about -0.955 degrees, not +0.96.",
)
v.check(
    "PMNS table delta_CP signed difference",
    delta_pred - delta_pdg,
    -0.57,
    abs_tol=0.02,
    detail="Expected fail under TOE - PDG convention: -66.43 - (-67.0) = +0.57 degrees.",
)
v.check("theta23 PMNS absolute sigma", abs(theta23_pred - theta23_pdg) / 0.83, 1.2, rel=5e-2)

sys.exit(v.summary())
