#!/usr/bin/env python3
"""
verify_P114.py -- Addendum 114: light-quark QCD scheme corrections.

This verifier checks the explicit residuals, EM renormalization estimates,
Peirce-block QCD correction, corrected u/d/s masses, sigma comparisons, and
the confinement-scale statement in 114_Addendum_LightQuarkQCD.tex.

The central d/s arithmetic reproduces: the 8/9 alpha_s/pi correction gives
about 3.356%, closing d and s at the quoted precision, and the u value remains
inside the broad PDG one-sigma interval. The main formula error is the
confinement-scale line: pi*mu0*m_e is about 220 MeV, not 1.27 MeV. The 1.27 MeV
number is close to pi*(mu1/mu0)*m_e. The scale-selection and u-quark
first-principles derivations remain explicitly open.
"""

from __future__ import annotations

import math
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
from verify_common import CheckResult, Verifier


class ModernVerifier(Verifier):
    """Local output adapter: tolerance logic byte-identical to
    verify_common.Verifier.check; emits the modern corpus line format
    ("  [PASS] {n:>2}. {desc}") with computed/claimed/tolerance values
    kept as indented info lines, and the modern RESULT footer."""

    def __init__(self, name: str):
        self.name = name
        self.results = []
        self._n = 0
        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 = abs(computed - claimed)
            err_detail = f"abs err={err:.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._emit(label, ok, computed, claimed, err_detail, detail)

    def record(self, label, ok, computed="", claimed="", detail=""):
        return self._emit(label, ok, computed, claimed, "", detail)

    def _emit(self, label, ok, computed, claimed, info, ann):
        full_detail = (info + (f"; {ann}" if ann else "")) if info else ann
        self.results.append(CheckResult(label, ok, computed, claimed, full_detail))
        self._n += 1
        desc = f"{label} -- {ann}" if ann else label
        print(f"  [{'PASS' if ok else 'FAIL'}] {self._n:>2}. {desc}")
        if computed != "" or claimed != "":
            print(f"        computed: {computed}")
            print(f"        claimed : {claimed}")
        if info:
            print(f"        {info}")
        return ok

    def summary(self):
        passed = sum(bool(r.ok) for r in self.results)
        failed = len(self.results) - passed
        print(f"\n{'='*60}\nRESULT: {passed} PASS / {failed} FAIL")
        return 1 if failed else 0


v = ModernVerifier("P114 -- Light Quark QCD Scheme Corrections")

ROOT = Path(__file__).resolve().parents[1]
TEX = (ROOT / "114_Addendum_LightQuarkQCD.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
ME_MEV = 0.51099895

ORBIT = {"u": 2.410, "d": 4.840, "s": 98.200}
PDG = {"u": 2.160, "d": 4.670, "s": 95.000}
ALPHA_A_NLO = 0.006002
ALPHA_S_MZ = 0.1186
DELTA_QCD = (8.0 / 9.0) * ALPHA_S_MZ / PI


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


v.check("initial u residual", pct(ORBIT["u"], PDG["u"]), 11.57, rel=5e-4)
v.check("initial d residual", pct(ORBIT["d"], PDG["d"]), 3.64, rel=8e-4)
v.check("initial s residual", pct(ORBIT["s"], PDG["s"]), 3.37, rel=8e-4)

z_mu = 1.0 + ALPHA_A_NLO
z_u = 1.0 + (4.0 / 9.0) * ALPHA_A_NLO
z_d = 1.0 + (1.0 / 9.0) * ALPHA_A_NLO
v.check("muon EM factor", z_mu, 1.006002, rel=1e-12)
v.check("u EM factor", z_u, 1.002667, rel=6e-7)
v.check("d/s EM factor", z_d, 1.000667, rel=8e-7)
v.check("u EM fractional shift percent", 100.0 * (z_u - 1.0), 0.27, rel=2e-2)
v.check("d/s EM fractional shift percent", 100.0 * (z_d - 1.0), 0.07, rel=5e-2)
v.record(
    "EM correction is too small to close light-quark residuals",
    (100.0 * (z_u - 1.0) < 0.3) and (100.0 * (z_d - 1.0) < 0.3),
    computed=f"u={100.0*(z_u-1.0):.4f}%, d/s={100.0*(z_d-1.0):.4f}%",
    claimed="<0.3% for all three",
)

v.check("P103 bottom correction", (4.0 / 9.0) * 0.2269 / PI, 0.0321, rel=8e-4)
v.check("QCD Peirce correction", DELTA_QCD, 0.03356, rel=3e-4)
v.check("QCD Peirce correction percent", 100.0 * DELTA_QCD, 3.356, rel=3e-4)

corrected = {q: mass * (1.0 - DELTA_QCD) for q, mass in ORBIT.items()}
v.check("corrected u mass", corrected["u"], 2.329, rel=3e-4)
v.check("corrected d mass", corrected["d"], 4.677, rel=2e-4)
v.check("corrected s mass", corrected["s"], 94.905, rel=8e-5)
v.check("corrected u residual", pct(corrected["u"], PDG["u"]), 7.83, rel=3e-3)
v.check("corrected d residual", pct(corrected["d"], PDG["d"]), 0.16, rel=4e-2)
v.check("corrected s residual", pct(corrected["s"], PDG["s"]), -0.10, rel=2e-2)
v.check("corrected u sigma using upper error", (corrected["u"] - PDG["u"]) / 0.49, 0.34, rel=2e-2)
v.check("uncorrected u sigma using upper error", (ORBIT["u"] - PDG["u"]) / 0.49, 0.51, rel=2e-2)
v.record(
    "u corrected mass lies inside quoted asymmetric one-sigma band",
    2.16 - 0.26 <= corrected["u"] <= 2.16 + 0.49,
    computed=corrected["u"],
    claimed="[1.90, 2.65] MeV",
)
v.record(
    "u orbit mass lies inside quoted asymmetric one-sigma band",
    2.16 - 0.26 <= ORBIT["u"] <= 2.16 + 0.49,
    computed=ORBIT["u"],
    claimed="[1.90, 2.65] MeV",
)

m_conf_claim_formula = PI * MU0 * ME_MEV
m_conf_mu_formula = PI * MU * ME_MEV
v.check(
    "confinement scale pi*mu0*m_e",
    m_conf_claim_formula,
    1.27,
    rel=1e-2,
    detail="Expected fail: pi*mu0*m_e is about 220 MeV, not 1.27 MeV.",
)
v.check("confinement scale pi*mu0*m_e known value", m_conf_claim_formula, 219.99, rel=5e-5)
v.check(
    "nearby pi*MU*m_e value",
    m_conf_mu_formula,
    1.27,
    rel=5e-3,
    detail="This explains the likely source of the 1.27 MeV number, but it is not the printed formula.",
)

v.record(
    "MZ scale selection is derived in P114",
    False,
    computed="the open-items section explicitly asks to derive the choice MZ for d/s versus mb for b from Peirce sector geometry",
    claimed="evaluation scale MZ follows from the correction theorem",
    detail="Expected status fail.",
)
v.record(
    "u-quark first-principles mass derivation is closed",
    False,
    computed="P114 says a first-principles u derivation from confinement-scale J3(O) structure remains the next step",
    claimed="u quark within uncertainty, but not closed",
    detail="Expected status fail.",
)
v.record(
    "d/s closure is independent of phenomenological scheme choice",
    False,
    computed="the numerical closure depends on the sign and scale choice of a proposed QCD scheme factor; the scale-selection principle remains open",
    claimed="d and s masses closed via Peirce block correction",
    detail="Expected proof-status fail: arithmetic closure reproduces, derivational closure is not complete.",
)

sys.exit(v.summary())
