#!/usr/bin/env python3
"""
verify_P036.py -- Addendum 36: sector energies and lepton mass ratios.

This verifier checks the sector-integral arithmetic, the muon near-prediction,
and the tau self-lensing claims. Most raw pi/moment numerics reproduce. The
main flagged issues are interpretive: the paper shifts from an absolute
Paper-18 mass formula to a re-anchored ratio formula, and the tau
E_self(lambda_tau) value is quoted without an explicit formula in P36.
"""

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("P036 -- Sector Energies and Lepton Mass Ratios")

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

PI = math.pi
MU0 = 4 * PI**3 + PI**2 + PI
MU1 = 16 * PI**3 / 5 + 3 * PI**2 / 4 + 2 * PI / 3
MU = MU1 / MU0
MUON_EXP = 206.7683
TAU_EXP = 3477.48
E_SELF_FULL = 13.177
E_SELF_QC = 13.617


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


v.check("mu0 = 4*pi^3 + pi^2 + pi", MU0, 137.036, rel=3e-6)
v.check("mu1 = 16*pi^3/5 + 3*pi^2/4 + 2*pi/3", MU1, 108.7167, rel=3e-7)
v.check("MU = mu1/mu0", MU, 0.793342, rel=5e-7)

e_edge = PI
e_boundary = PI**2
e_bulk = 4 * PI**3
v.check("edge sector integral", e_edge, PI, rel=1e-12)
v.check("boundary sector integral", e_boundary, PI**2, rel=1e-12)
v.check("bulk sector integral", e_bulk, 4 * PI**3, rel=1e-12)
v.check("sector energies sum to mu0", e_edge + e_boundary + e_bulk, MU0, rel=1e-12)
v.check("f_e percent", 100 * e_edge / MU0, 2.293, rel=5e-4)
v.check("f_mu percent", 100 * e_boundary / MU0, 7.202, rel=5e-4)
v.check("f_tau bulk percent", 100 * e_bulk / MU0, 90.505, rel=5e-5)
v.check("f_mu/f_e = pi", (e_boundary / MU0) / (e_edge / MU0), PI, rel=1e-12)
v.check("f_tau/f_mu = 4*pi", (e_bulk / MU0) / (e_boundary / MU0), 4 * PI, rel=1e-12)

v.check("S3 gap 3 mass ratio", math.exp(MU * 3), 10.8, rel=5e-3)
v.check("S3 gap 5 mass ratio", math.exp(MU * 5), 53, rel=5e-3)
v.check("S3 gap 8 mass ratio", math.exp(MU * 8), 572, rel=5e-3)
muon_ratio = math.exp(MU * (PI**2 - PI))
v.check("muon sector-integral mass ratio", muon_ratio, 208.016, rel=5e-6)
v.check("muon residual percent", pct(muon_ratio, MUON_EXP), 0.60, rel=1e-2)

v.record(
    "absolute Paper-18 formula is consistent with electron anchor E_e=pi",
    abs(math.exp(MU * PI) - 1) < 1e-12,
    f"exp(MU*pi)={math.exp(MU * PI):.6f}",
    "1",
    "Expected fail: the original m_n=m_e exp(MU E_n) would not give m_e at E_e=pi; the later ratio formula is a re-anchoring.",
)

tau_needed = PI + math.log(TAU_EXP) / MU
v.check("tau energy required by experimental ratio", tau_needed, 13.420, rel=5e-5)
v.check("tau pi-tower fractional index", math.log(13.420) / math.log(PI), 2.268, rel=5e-4)
v.check("tau candidate pi*(pi+1)", PI * (PI + 1), 13.011, rel=5e-5)
v.check("tau candidate 4*pi^2/3", 4 * PI**2 / 3, 13.159, rel=5e-5)
v.check("tau candidate pi^2 + pi/2", PI**2 + PI / 2, 11.440, rel=5e-5)
v.check("tau candidate 4*pi - pi/10", 4 * PI - PI / 10, 12.252, rel=5e-5)

lambda_tau = MU1 / (MU0 + MU1)
v.check("lambda_tau", lambda_tau, 0.44238, rel=5e-5)
v.check("fixed-point identity lambda/(1-lambda)", lambda_tau / (1 - lambda_tau), MU, rel=1e-12)

# P36 does not print a formula for E_self(lambda). The simplest linear
# interpolation consistent with its endpoint wording, lambda=1 -> 13.177 and
# lambda=0 -> 13.617, does not give the quoted 13.4187.
tau_e_linear = lambda_tau * E_SELF_FULL + (1 - lambda_tau) * E_SELF_QC
tau_ratio_linear = math.exp(MU * (tau_e_linear - PI))
v.check(
    "tau E_self(lambda_tau) from endpoint-linear interpretation",
    tau_e_linear,
    13.4187,
    rel=1e-4,
    detail="Expected fail: endpoint-linear interpolation gives about 13.42235; P36 does not print the nonlinear self-lensing formula needed for 13.4187.",
)
v.check(
    "tau mass ratio from endpoint-linear interpretation",
    tau_ratio_linear,
    3474.6,
    rel=5e-4,
    detail="Expected fail: endpoint-linear interpolation gives about 3484.8.",
)
v.check("tau mass ratio from quoted E_tau=13.4187", math.exp(MU * (13.4187 - PI)), 3474.6, rel=5e-5)
v.check("tau quoted residual percent", pct(math.exp(MU * (13.4187 - PI)), TAU_EXP), -0.08, rel=2e-2)

v.record(
    "P36 contains an explicit formula for E_self(lambda_tau)",
    "E_{\\mathrm{self}}(\\lambda)" in TEX and "13.4187" not in TEX,
    "P36 quotes E_self(lambda_tau)=13.4187 but does not define the function in this file",
    "explicit formula",
    "Expected fail: the tau closure is only externally verifiable from Paper 04, not from the P36 TeX alone.",
)
v.record(
    "status wording keeps the muon/tau theorem conditional",
    "All inputs are proven. No step requires fitting or physical identification." not in TEX,
    "paper says all inputs are proven, while earlier it calls the sector-energy identification a numerical observation/conjecture",
    "conditional status",
    "Expected fail: the status section overstates the proof level relative to the paper's own muon-status remark.",
)

sys.exit(v.summary())
