#!/usr/bin/env python3
"""
verify_P120.py -- Addendum 120: u-quark mass from confinement scale.

This verifier checks P120's documented closure attempt for m_u: the P114 QCD
correction, corrected u/d/s masses, PDG-band comparisons, pi*MU*m_e confinement
scale, m_u/m_conf ratio, candidate-ratio table, and open-problem status.

The main result is internally consistent as an open item: both the bare orbit
and Peirce-corrected u mass are inside the quoted one-sigma band, while no listed
TOE-native candidate closes m_u/m_conf within 1%. The flagged issues are limited:
the "all TOE-native quantities exhausted" wording is broader than the finite table,
the alpha*m_N estimate is not 1.3 MeV if m_N is a nucleon mass, and being inside a
broad experimental band should not be phrased as pinning/predicting the band.
"""

from __future__ import annotations

import math
import sys
from pathlib import Path

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:
    """Target-style output adapter; check/record numerics are unchanged."""

    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,
                           err_detail + (f"; {detail}" if detail else ""))

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

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


v = Verifier("P120 -- m_u Confinement Open Closure")

ROOT = Path(__file__).resolve().parents[1]
TEX = (ROOT / "120_Addendum_mUConfinement.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
ME = 0.51100

ORBIT_U = 2.410
ORBIT_D = 4.840
ORBIT_S = 98.200
PDG_U = 2.160
PDG_D = 4.670
PDG_U_LOW = 1.90
PDG_U_HIGH = 2.65
DELTA = (8.0 / 9.0) * ALPHA_S / PI
U_QCD = ORBIT_U * (1.0 - DELTA)
D_QCD = ORBIT_D * (1.0 - DELTA)
S_QCD = ORBIT_S * (1.0 - DELTA)
M_CONF = PI * MU * ME
RATIO = ORBIT_U / M_CONF


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


def candidate_gap(value: float) -> float:
    return 100.0 * (value - RATIO) / RATIO


v.check("MU", MU, 0.79334, rel=3e-6)
v.check("Peirce QCD correction percent", 100.0 * DELTA, 3.356, rel=3e-4)
v.check("corrected u mass", U_QCD, 2.329, rel=3e-4)
v.check("corrected d mass", D_QCD, 4.677, rel=2e-4)
v.check("corrected s mass", S_QCD, 94.905, rel=8e-5)
v.check("orbit u residual percent", pct(ORBIT_U, PDG_U), 11.6, rel=3e-3)
v.check("QCD u residual percent", pct(U_QCD, PDG_U), 7.83, rel=3e-3)
v.record("orbit u within one-sigma band", PDG_U_LOW <= ORBIT_U <= PDG_U_HIGH, ORBIT_U, "[1.90,2.65]")
v.record("QCD u within one-sigma band", PDG_U_LOW <= U_QCD <= PDG_U_HIGH, U_QCD, "[1.90,2.65]")
v.check("QCD u sigma above central", (U_QCD - PDG_U) / 0.49, 0.34, rel=2e-2)

v.check("m_conf = pi*MU*m_e", M_CONF, 1.273, rel=6e-4)
v.check("orbit u over m_conf", RATIO, 1.893, rel=6e-4)
v.check("candidate 2 deviation percent", candidate_gap(2.0), 5.7, rel=2e-2)
v.check("candidate 1+MU value", 1.0 + MU, 1.793, rel=2e-4)
v.check("candidate 1+MU deviation percent", candidate_gap(1.0 + MU), -5.3, rel=2e-2)
v.check("candidate 1/MU^2 value", 1.0 / MU**2, 1.589, rel=4e-4)
v.check("candidate 1/MU^2 deviation percent", candidate_gap(1.0 / MU**2), -16.0, rel=3e-3)
v.check("candidate phi^2", ((1.0 + math.sqrt(5.0)) / 2.0) ** 2, 2.618, rel=2e-4)
v.check("candidate e deviation percent", candidate_gap(math.e), 44.0, rel=1e-2)
v.check("candidate pi deviation percent", candidate_gap(PI), 66.0, rel=5e-3)
v.check("candidate 1+pi*alpha", 1.0 + PI * ALPHA, 1.023, rel=8e-5)
v.check("candidate 1+alpha_s/3", 1.0 + ALPHA_S / 3.0, 1.040, rel=5e-4)

v.check("PDG central u-d split", PDG_D - PDG_U, 2.52, rel=5e-3)
v.check("orbit u-d split", ORBIT_D - ORBIT_U, 2.430, rel=1e-12)
v.check(
    "alpha times nucleon mass estimate",
    ALPHA * 938.9,
    1.3,
    rel=1e-1,
    detail="Expected fail: if m_N is a nucleon mass, alpha*m_N is about 6.85 MeV, not 1.3 MeV.",
)

listed_candidates = [
    2.0,
    1.0 + MU,
    1.0 / MU**2,
    ((1.0 + math.sqrt(5.0)) / 2.0) ** 2,
    math.e,
    PI,
    1.0 + PI * ALPHA,
    1.0 + ALPHA_S / 3.0,
]
best_gap = min(abs(candidate_gap(x)) for x in listed_candidates)
v.check("best listed candidate absolute deviation percent", best_gap, 5.3, rel=3e-2)
v.record(
    "listed candidates fail the <1% closure threshold",
    best_gap > 1.0,
    computed=f"best listed gap = {best_gap:.3f}%",
    claimed="no listed ratio closes m_u/m_conf",
)
v.record(
    "all TOE-native ratios have been exhausted",
    False,
    computed="P120 tests a finite candidate table; it does not define an exhaustive grammar/search over all TOE-native expressions",
    claimed="all TOE-native dimensionless quantities at the relevant scale exhausted",
    detail="Expected scope fail.",
)
v.record(
    "P120 correctly documents m_u as open rather than closed",
    "documented open item" in TEX and "not yet derived" in TEX,
    computed="documented open item / J1-J1 propagator not yet derived",
    claimed="open precision frontier",
)
v.record(
    "inside one-sigma means central value is pinned",
    False,
    computed="the one-sigma interval width is about 0.75 MeV, much larger than the remaining 0.169 MeV corrected central gap",
    claimed="framework predicts the right one-sigma band but does not yet pin the central value",
    detail="Expected wording/status fail: consistency with a broad band is weaker than a central-value prediction.",
)

sys.exit(v.summary())
