#!/usr/bin/env python3
"""
verify_P116.py -- Addendum 116: tau mass from P13 Peirce geometry.

This verifier checks the P13 walk amplitude, MU/lambda_tau arithmetic,
lambda-scaled self-lensing energy, tau/electron mass ratio, tau mass conversion,
and selected status claims in 116_Addendum_TauMassPeirce.tex.

The headline tau/electron ratio arithmetic reproduces: lambda_tau, E_self(lambda),
and exp(MU*(E_self-pi)) give 3474.61, about -0.075% versus the quoted PDG ratio.
Flagged issues are a local MU typo, a tau-MeV table mismatch, and proof-status
claims: P13-as-Hopf-S1, fold-map detailed balance, and all-leptons-first-principles
closure are asserted more strongly than the derivation supports.
"""

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):
    """Output adapter: modern check-line format. Tolerance logic is
    inherited unchanged from verify_common.Verifier; only printing and
    the footer differ."""

    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)
        expected = (not ok) and ("Expected" in str(detail))
        desc = f"{label} -- {detail}" if expected else label
        print(f"  [{'PASS' if ok else 'FAIL'}] {n:>2}. {desc}")
        if computed != "" or claimed != "":
            print(f"       computed: {computed}")
            print(f"       claimed : {claimed}")
        if detail and not expected:
            print(f"       {detail}")
        return ok

    def summary(self):
        passed = sum(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("P116 -- Tau Mass from P13 Peirce")

ROOT = Path(__file__).resolve().parents[1]
TEX = (ROOT / "116_Addendum_TauMassPeirce.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
LAMBDA_TAU = MU / (1.0 + MU)
M_E = 0.51099895
PDG_RATIO = 3477.23


def e_self(lam: float) -> float:
    energy = 0.5 * (
        2304.0 * PI**6 / 5.0
        + 12.0 * PI**4
        + 4.0 * PI**2 * lam**2
        + 144.0 * PI**5
        + 64.0 * PI**4 * lam
        + 12.0 * PI**3 * lam
    )
    mu0_lam = 4.0 * PI**3 + PI**2 + PI * lam
    return energy / mu0_lam**2


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


walk_p13 = math.cos(3.0 * PI / 14.0) ** 2 * math.cos(6.0 * PI / 14.0)
walk_p13_alt = math.sin(2.0 * PI / 7.0) ** 2 * math.sin(PI / 14.0)
walk_p23 = math.cos(PI / 14.0) ** 2 * math.cos(2.0 * PI / 14.0)
e_tau = e_self(LAMBDA_TAU)
tau_ratio = math.exp(MU * (e_tau - PI))
tau_mev = tau_ratio * M_E

v.check("P13 walk amplitude", walk_p13, 0.1358, rel=2e-3)
v.check("P13 complementary-angle identity", walk_p13_alt, walk_p13, rel=1e-12)
v.check("MU", MU, 0.79334, rel=3e-6)
v.check(
    "printed MU=0.79384",
    MU,
    0.79384,
    rel=1e-4,
    detail="Expected fail: corpus MU is about 0.793342, not 0.79384.",
)
v.check("lambda_tau", LAMBDA_TAU, 0.44238, rel=5e-6)
v.check("E_self(lambda=0)", e_self(0.0), 13.617, rel=4e-6)
v.check("E_self(lambda_tau)", e_tau, 13.419, rel=3e-5)
v.check("E_self(lambda=1)", e_self(1.0), 13.177, rel=3e-5)
v.check("tau exponent", MU * (e_tau - PI), 8.153, rel=1e-4)
v.check("tau/e ratio", tau_ratio, 3474.6, rel=5e-6)
v.check("tau/e residual percent", pct(tau_ratio, PDG_RATIO), -0.075, rel=5e-2)
v.check(
    "tau mass in MeV from predicted ratio",
    tau_mev,
    1776.4,
    rel=1e-4,
    detail="Expected fail: 3474.6 times the electron mass is about 1775.5 MeV, not 1776.4 MeV.",
)
v.check("P23 walk amplitude", walk_p23, 0.85636, rel=5e-6)
v.check("alpha times P23 walk amplitude", ALPHA * walk_p23, 6.0e-3, rel=5e-2)

v.record(
    "P13 block is literally the Hopf S1 fiber",
    False,
    computed="P13 is an 8-real-dimensional octonionic Peirce block, whereas a Hopf S1 fiber is one-dimensional; the paper asserts an algebraic representative relation rather than deriving an isomorphism",
    claimed="P13 is precisely the Hopf S1 fiber",
    detail="Expected structural-identification fail.",
)
v.record(
    "fold-map detailed-balance equation is derived from operator dynamics",
    False,
    computed="mu1*(1-lambda)=mu0*lambda is introduced as the fixed-point condition, but no fold-map flux/operator calculation is supplied",
    claimed="detailed balance selects lambda_tau",
    detail="Expected proof-status fail.",
)
v.record(
    "charged lepton sector is fully first-principles closed",
    False,
    computed="electron mass is still an anchor, the muon result is inherited, tau residual remains and two-loop P13 correction is listed as open",
    claimed="all three charged leptons derived from first principles without free parameters",
    detail="Expected status fail.",
)
v.record(
    "tau sigma residual is reproducible from supplied uncertainty",
    False,
    computed="the TeX quotes -0.26 sigma but does not provide the tau/e uncertainty used to compute it",
    claimed="-0.26 sigma",
    detail="Expected reproducibility fail.",
)

sys.exit(v.summary())
