#!/usr/bin/env python3
"""
verify_P113.py -- Addendum 113: muon EM renormalization.

This verifier checks P113's muon mass correction:
LO = exp(MU*(pi^2-pi)), A_NLO from the P81 fold amplitude, Z_mu =
1 + alpha*A_NLO, and the final ratio LO/Z_mu.

The printed rounded-MU route reproduces the headline near-closure. Using the
exact corpus MU = mu1/mu0 gives a slightly different result: 206.775 rather
than 206.769, so the "exact" +0.0005% residual and 1200x improvement are
stale/overstated. The structural closure is also explicitly incomplete because
the first-principles derivation of Z_mu is listed as 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 adapter: identical tolerance logic, modern output format."""

    def __init__(self, name: str):
        self.name = name
        self.results = []
        print(name)

    def record(self, label, ok, computed="", claimed="", detail=""):
        self.results.append(CheckResult(label, ok, computed, claimed, detail))
        n = len(self.results)
        desc, info = label, detail
        i = detail.find("Expected")
        if i >= 0:
            desc = f"{label} -- {detail[i:]}"
            info = 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 info:
            print(f"        {info}")
        return bool(ok)

    def summary(self) -> int:
        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("P113 -- Muon EM Renormalization")

ROOT = Path(__file__).resolve().parents[1]
TEX = (ROOT / "113_Addendum_MuonEMRenorm.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_EXACT = MU1 / MU0
MU_PRINTED = 0.793338
ALPHA = 1.0 / MU0
LAMBDA = math.sin(PI / 14.0)
A_LO = math.cos(PI / 14.0) ** 2 * math.cos(2.0 * PI / 14.0)
A_NLO = A_LO * (1.0 - 4.0 * LAMBDA**2 / 5.0)
Z_MU = 1.0 + ALPHA * A_NLO
PDG_RATIO = 206.768
M_E = 0.51099895

LO_EXACT = math.exp(MU_EXACT * (PI**2 - PI))
LO_PRINTED = math.exp(MU_PRINTED * (PI**2 - PI))
RATIO_EXACT = LO_EXACT / Z_MU
RATIO_PRINTED = LO_PRINTED / Z_MU
M_MU_EXACT = RATIO_EXACT * M_E
M_MU_PRINTED = RATIO_PRINTED * M_E
SCREEN = MU0 / (MU0 + A_NLO)
SELF_ENERGY_PERCENT = -100.0 * (ALPHA * A_NLO) / (1.0 + ALPHA * A_NLO)


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


v.check("mu0 alpha inverse", MU0, 137.036, rel=3e-6)
v.check(
    "printed MU value",
    MU_EXACT,
    MU_PRINTED,
    rel=2e-6,
    detail="Expected fail: corpus MU is about 0.793342208, not 0.793338.",
)
v.check("lambda = sin(pi/14)", LAMBDA, 0.22252, rel=5e-5)
v.check("A_LO fold amplitude", A_LO, 0.85636, rel=5e-6)
v.check("A_NLO fold amplitude", A_NLO, 0.82243, rel=6e-6)
v.check("alpha", ALPHA, 0.0072973, rel=5e-6)
v.check("alpha*A_NLO", ALPHA * A_NLO, 6.00158e-3, rel=2e-6)
v.check("Z_mu", Z_MU, 1.006002, rel=5e-7)
v.check("screening form 1/Z", SCREEN, 1.0 / Z_MU, rel=1e-12)

v.check("LO muon ratio with printed MU", LO_PRINTED, 208.0103, rel=3e-7)
v.check("LO residual with printed MU percent", pct(LO_PRINTED, PDG_RATIO), 0.601, rel=2e-3)
v.check(
    "LO muon ratio with exact MU",
    LO_EXACT,
    208.0103,
    rel=1e-5,
    detail="Expected fail: exact corpus MU gives about 208.0161.",
)
v.check("P113 ratio with printed MU", RATIO_PRINTED, 206.769, rel=2e-6)
v.check("P113 residual with printed MU percent", pct(RATIO_PRINTED, PDG_RATIO), 0.0005, rel=4e-1)
v.check("P113 muon mass with printed MU", M_MU_PRINTED, 105.659, rel=2e-6)
v.check(
    "P113 ratio with exact corpus MU",
    RATIO_EXACT,
    206.769,
    rel=5e-6,
    detail="Expected fail: exact corpus MU gives about 206.7752.",
)
v.check(
    "P113 residual with exact corpus MU percent",
    pct(RATIO_EXACT, PDG_RATIO),
    0.0005,
    rel=5e-1,
    detail="Expected fail: exact corpus MU residual is about +0.00347%.",
)
v.check(
    "P113 muon mass with exact corpus MU",
    M_MU_EXACT,
    105.659,
    rel=5e-6,
    detail="Expected fail: exact corpus MU gives about 105.6619 MeV.",
)
v.check("EM self-energy percent", SELF_ENERGY_PERCENT, -0.59659, rel=3e-5)

improvement_exact = abs(pct(LO_EXACT, PDG_RATIO) / pct(RATIO_EXACT, PDG_RATIO))
v.check(
    "improvement factor using exact corpus MU",
    improvement_exact,
    1200.0,
    rel=2e-1,
    detail="Expected fail: exact-corpus route improves by about 174x, not 1200x.",
)
v.record(
    "Z_mu first-principles derivation remains open",
    "Derive $Z_\\mu$ from first principles" in TEX and "remains open" in TEX,
    computed="open item present",
    claimed="Z_mu structural derivation not yet supplied",
)
v.record(
    "Z_mu is derived from first principles in P113",
    False,
    computed="P113 establishes a numerical renormalization ansatz but lists its first-principles derivation as open",
    claimed="single EM renormalization factor closes from TOE geometry",
    detail="Expected proof-status fail.",
)
v.record(
    "muon open problem is exactly closed",
    False,
    computed="headline closure depends on stale rounded MU and an open Z_mu derivation; exact-corpus residual is small but not the quoted +0.0005%",
    claimed="Muon open problem: CLOSED / closes exactly",
    detail="Expected status fail.",
)
v.record(
    "all charged leptons are fully accounted for",
    False,
    computed="electron is an anchor, P116 flags tau proof-status issues, and P113 leaves Z_mu derivation open",
    claimed="three charged leptons are now fully accounted for",
    detail="Expected status fail.",
)

sys.exit(v.summary())
