#!/usr/bin/env python3
"""
verify_P119.py -- Addendum 119: rho EM self-energy.

This verifier checks the rho^0 VMD correction arithmetic in
119_Addendum_RhoEMSelfEnergy.tex: the J1 bare 8*pi coupling, monadic
integral pi, delta_rho = pi*alpha, corrected f_rho^2, charge-factor
suppression, omega/phi table values, and the correction hierarchy.

The main rho correction is numerically reproducible. Flagged issues are
sign/rounding/status problems: the exact TOE-minus-PDG rho residual is
negative, the exact gap-closed fraction slightly overshoots 100% rather
than giving 99.6%, the abstract/body residual sign conventions conflict,
and the "complete sector" wording is stronger than the paper's own open
items about omega/phi residuals and monadic-term selection.
"""

from __future__ import annotations

import math
import sys
from pathlib import Path



PASS = FAIL = 0
_N = 0

def record(label, ok, computed="", claimed="", detail=""):
    """Modern-format check line; behavior-preserving port of verify_common."""
    global PASS, FAIL, _N
    _N += 1
    ok = bool(ok)
    desc = label
    if ok:
        PASS += 1
    else:
        FAIL += 1
        if "Expected" in detail:
            i = detail.find("Expected")
            desc = f"{label} -- {detail[i:]}"
            detail = detail[:i].rstrip().rstrip(";")
    print(f"  [{'PASS' if ok else 'FAIL'}] {_N:>2}. {desc}")
    if computed != "" or claimed != "":
        print(f"        computed: {computed}")
        print(f"        claimed : {claimed}")
    if detail:
        print(f"        {detail}")
    return ok

def check(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 record(label, ok, computed, claimed, err_detail + (f"; {detail}" if detail else ""))

print("P119 -- rho EM Self-Energy")

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

PI = math.pi
MU0 = 4.0 * PI**3 + PI**2 + PI
MU1 = 16.0 * PI**3 / 5.0 + 3.0 * PI**2 / 4.0 + 2.0 * PI / 3.0
MU = MU1 / MU0
ALPHA = 1.0 / MU0
ALPHA_S = 0.1186

PDG_RHO = 24.56
PDG_OMEGA = 290.97
PDG_PHI = 179.1

C_RHO2 = 1.0 / 2.0
C_OMEGA2 = 1.0 / 18.0
C_PHI2 = 1.0 / 9.0

J1_BARE = 8.0 * PI
MONADIC_INTEGRAL = PI
DELTA_RHO = PI * ALPHA
F_RHO = J1_BARE * (1.0 - DELTA_RHO)
RHO_ORIGINAL_GAP = 100.0 * (J1_BARE - PDG_RHO) / J1_BARE
RHO_RESIDUAL = 100.0 * (F_RHO - PDG_RHO) / PDG_RHO
GAP_CLOSED = 100.0 * (J1_BARE - F_RHO) / (J1_BARE - PDG_RHO)

F_OMEGA = 72.0 * PI / (1.0 - ALPHA_S) ** 2
F_PHI = 36.0 * PI / MU**2
OMEGA_RESIDUAL = 100.0 * (F_OMEGA - PDG_OMEGA) / PDG_OMEGA
PHI_RESIDUAL = 100.0 * (F_PHI - PDG_PHI) / PDG_PHI
OMEGA_EM = DELTA_RHO / 9.0
F_OMEGA_WITH_EM = F_OMEGA * (1.0 - OMEGA_EM)
OMEGA_WITH_EM_RESIDUAL = 100.0 * (F_OMEGA_WITH_EM - PDG_OMEGA) / PDG_OMEGA
PEIRCE_GEOM_CORRECTION = 1.0 / MU**2 - 1.0


def pct(value: float, target: float) -> float:
    return 100.0 * (value - target) / abs(target)


check("alpha inverse mu0", MU0, 137.036, rel=3e-6)
check("bare J1 f_rho^2 = 8*pi", J1_BARE, 25.133, rel=2e-5)
check("P108 original gap magnitude percent", RHO_ORIGINAL_GAP, 2.28, rel=5e-3)
record(
    "P108 bare value overshoots PDG rho",
    J1_BARE > PDG_RHO,
    computed=f"bare={J1_BARE:.6f}, PDG={PDG_RHO:.2f}",
    claimed="bare overshoots by 2.28%",
)
check("monadic spectral integral", MONADIC_INTEGRAL, PI, rel=1e-12)
check("delta_rho = pi*alpha", DELTA_RHO, 0.022917, rel=5e-4)
check("1 - pi*alpha", 1.0 - DELTA_RHO, 0.977083, rel=1e-5)
check("corrected f_rho^2", F_RHO, 24.557, rel=2e-5)
check(
    "rho residual sign and value percent",
    RHO_RESIDUAL,
    0.01,
    rel=1e-1,
    detail="Expected fail: exact TOE-minus-PDG convention gives about -0.014%, not +0.01%.",
)
check(
    "gap closed percent",
    GAP_CLOSED,
    99.6,
    rel=2e-3,
    detail="Expected fail: exact values slightly overclose the gap, giving about 100.6%.",
)

check("rho charge factor squared", C_RHO2, 1.0 / 2.0, rel=1e-12)
check("omega charge factor squared", C_OMEGA2, 1.0 / 18.0, rel=1e-12)
check("phi charge factor squared", C_PHI2, 1.0 / 9.0, rel=1e-12)
check("omega-to-rho EM suppression", C_OMEGA2 / C_RHO2, 1.0 / 9.0, rel=1e-12)
check("omega EM self-energy percent", 100.0 * OMEGA_EM, 0.25, rel=3e-2)

check("omega f_V^2 table value", F_OMEGA, 291.2, rel=2e-4)
check("omega residual percent", OMEGA_RESIDUAL, 0.08, abs_tol=0.025)
check("phi f_V^2 table value", F_PHI, 179.7, rel=7e-4)
check("phi residual percent", PHI_RESIDUAL, 0.36, rel=1e-1)
check("Peirce geometry correction 1/MU^2 - 1", PEIRCE_GEOM_CORRECTION, 0.589, rel=4e-4)
record(
    "correction hierarchy",
    DELTA_RHO < ALPHA_S / 3.0 < PEIRCE_GEOM_CORRECTION,
    computed=f"{DELTA_RHO:.6f} < {ALPHA_S/3.0:.6f} < {PEIRCE_GEOM_CORRECTION:.6f}",
    claimed="pi alpha < alpha_s/3 < 1/MU^2 - 1",
)
check("omega residual after adding suppressed EM percent", OMEGA_WITH_EM_RESIDUAL, -0.19, rel=8e-2)

record(
    "abstract and body use consistent original residual sign",
    False,
    computed="abstract says -2.28% discrepancy; setup formula computes +2.28% bare-minus-exp",
    claimed="one consistent P108 rho residual sign convention",
    detail="Expected sign-convention fail.",
)
record(
    "neutral vector f_V^2 sector is fully closed at this level",
    False,
    computed="open items state omega/phi residuals are not closed at this level and omega EM needs a more careful isoscalar treatment",
    claimed="This completes the neutral vector meson f_V^2 sector",
    detail="Expected status fail.",
)
record(
    "monadic-term selection is derived from J3(O) propagator formalism",
    False,
    computed="the open-items section says this is argued physically but has not been derived from the propagator formalism",
    claimed="self-energy uniquely picks the monadic term",
    detail="Expected proof-status fail.",
)
record(
    "open-items caveats are present in TeX",
    "not closed at this level" in TEX and "has not been" in TEX,
    computed="explicit caveats found",
    claimed="paper records residual and propagator-selection caveats",
)

print(f"\n{'='*60}\nRESULT: {PASS} PASS / {FAIL} FAIL")
sys.exit(0 if FAIL == 0 else 1)
