#!/usr/bin/env python3
"""
verify_P101.py -- Addendum 101: Higgs NNLO from the Freudenthal triple product.

This verifier checks the Freudenthal/Bryant arithmetic, the Higgs NNLO
coefficient arithmetic, the PDG target coefficient, the topology-(b) estimate,
and selected proof-status claims in 101_Addendum_FreudenthalNNLO.tex.

The headline c4^(c)=-18/5 and m_H~=125.09 GeV arithmetic reproduce. The flagged
issues are mostly target/proof issues: c4_req=-2.945 is not the central-value
coefficient for m_H=125.20 GeV, the exact mass is just below the strict one-sigma
lower edge, the stated c4 and c6 sensitivity estimates are off, the G2 average
calculation is an independent sphere average rather than the orbit average of a
fixed Fano triple, and the F4 orbit-factor proof treats the full 27-dimensional
Albert algebra as irreducible even though F4 fixes the identity/trace line.
"""

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("P101 -- Freudenthal NNLO Higgs")

PI = math.pi
V_EW = 246.22
M_H_PDG = 125.20
SIGMA_H = 0.11
LAM = math.sin(PI / 14)
LAM2 = LAM**2
LAM4 = LAM2**2
LAM6 = LAM4 * LAM2


def higgs_mass(c4: float = 0.0, c6: float = 0.0) -> float:
    radicand = 1 + 4 * LAM2 / 5 + c4 * LAM4 + c6 * LAM6
    return (V_EW / 2) * math.sqrt(radicand)


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


v.check("lambda = sin(pi/14)", LAM, 0.22252, rel=5e-6)
v.check("lambda^2", LAM2, 0.049516, rel=1e-5)
v.check("lambda^4", LAM4, 0.0024518, rel=5e-5)
v.check("lambda^6", LAM6, 0.000122, rel=5e-3)
v.check("4 lambda^2 / 5", 4 * LAM2 / 5, 0.039613, rel=2e-5)

# Freudenthal/Bryant arithmetic.
unit_triangle = 1 / 6
ordered_fano_triples = 7 * 6
independent_sphere_avg_reuvw_sq = ordered_fano_triples / 7**3
independent_sphere_avg_n3_sq = independent_sphere_avg_reuvw_sq / 36
fixed_fano_orbit_avg_n3_sq = unit_triangle**2

v.check("unit triangle amplitude", unit_triangle, 1 / 6, rel=0)
v.check("Bryant form unordered norm squared", 7, 7, rel=0)
v.check("Bryant ordered nonzero triples", ordered_fano_triples, 42, rel=0)
v.check("independent isotropic average of Re(uvw*)^2", independent_sphere_avg_reuvw_sq, 6 / 49, rel=1e-12)
v.check("independent isotropic average of n3^2", independent_sphere_avg_n3_sq, 1 / 294, rel=1e-12)
v.check(
    "G2 orbit average of fixed Fano triangle equals 1/294",
    fixed_fano_orbit_avg_n3_sq,
    1 / 294,
    rel=1e-6,
    detail="Expected fail: applying the same G2 element to a fixed Fano triple preserves the Bryant 3-form, giving (1/6)^2; 1/294 is an independent S^6 x S^6 x S^6 average.",
)

# Adjugate / nullspace arithmetic.
v.record("F# for F=E22-E33 is -E11", True, "diag(0,1,-1)# = diag(-1,0,0)", "-E11")
v.record("direct Higgs coupling <E22-E33, E22+E33> vanishes", True, "1 - 1 = 0", "0")
v.record("E11# vanishes for primitive idempotent", True, "E11 - E11 + 0*I = 0", "0")

# Orbit-factor proof audit.
v.record(
    "F4 acts irreducibly on all 27 dimensions of J3(O)",
    False,
    "Aut(J3(O)) fixes the identity/trace line; the usual nontrivial irreducible representation is the 26-dimensional traceless part.",
    "irreducible 27-dimensional representation",
    "Expected proof-audit fail: using d=27 via irreducibility needs a separate argument or should be replaced by the traceless/orbit representation actually used.",
)
v.record(
    "diagonal idempotents are in the same F4 orbit as off-diagonal generators",
    False,
    "Trace is F4-invariant: Tr(Eii)=1 while off-diagonal generators have trace 0.",
    "same orbit",
    "Expected proof-audit fail: trace separates these elements, so the orbit-count argument cannot literally count one loop per all 27 basis directions.",
)
v.record(
    "orbit factor 27 follows from the displayed Schur/orbit proof",
    False,
    "The proof mixes a scalar cubic/trilinear amplitude, a quadratic Schur formula, and basis summation including diagonal elements that do not enter n3 directly.",
    "Nc=27 proved",
    "Expected proof-audit fail: 27 may be a chosen normalization, but it is not derived by the displayed argument.",
)

# NNLO coefficient and mass arithmetic.
c4a = 16 / 25
c4c = -18 / 5
c4_p101 = c4a + c4c
radicand = 1 + 4 * LAM2 / 5 + c4_p101 * LAM4
mass = higgs_mass(c4_p101)
mass_nlo = higgs_mass(0)

v.check("topology a c4", c4a, 0.640, rel=1e-12)
v.check("topology c c4 = -(4/5)(1/6)(27)", -(4 / 5) * (1 / 6) * 27, -18 / 5, rel=1e-12)
v.check("combined P101 c4 = 16/25 - 18/5", c4_p101, -74 / 25, rel=1e-12)
v.check("combined P101 c4 decimal", c4_p101, -2.960, rel=1e-12)
v.check("74 lambda^4 / 25", 74 * LAM4 / 25, 0.007257, rel=5e-5)
v.check("P101 NNLO radicand", radicand, 1.032356, rel=5e-6)
v.check("P101 sqrt radicand", math.sqrt(radicand), 1.01604, rel=1e-5)
v.check("LO Higgs mass v/2", V_EW / 2, 123.11, rel=5e-5)
v.check("NLO Higgs mass", mass_nlo, 125.53, abs_tol=0.01)
v.check("P101 NNLO Higgs mass", mass, 125.09, abs_tol=0.005)
v.check("P101 residual GeV", mass - M_H_PDG, -0.11, abs_tol=0.006)
v.check("P101 residual sigma", (mass - M_H_PDG) / SIGMA_H, -1.0, rel=5e-2)
v.check("P101 residual percent", rel_pct(mass, M_H_PDG), -0.09, rel=3e-2)
v.record(
    "P101 exact mass lies inside strict one-sigma interval",
    abs(mass - M_H_PDG) <= SIGMA_H,
    f"mass={mass:.9f}, lower={M_H_PDG - SIGMA_H:.9f}",
    "[125.09, 125.31]",
    "Expected fail: exact arithmetic is about 0.0042 GeV below the lower edge; rounded 125.09 sits on the displayed boundary.",
)

# PDG target coefficient and sensitivity.
target_factor = (2 * M_H_PDG / V_EW) ** 2
c4_req_central = (target_factor - (1 + 4 * LAM2 / 5)) / LAM4
mass_from_claimed_req = higgs_mass(-2.945)
dm_dc4 = (V_EW / 2) * LAM4 / (2 * math.sqrt(radicand))
dc4_claimed_gap = -2.945 - c4_p101

v.check(
    "PDG central c4_req from m_H=125.20",
    c4_req_central,
    -2.945,
    rel=5e-3,
    detail="Expected fail: central closure requires c4 about -2.1906 in this signed convention; -2.945 produces the lower edge.",
)
v.check(
    "mass produced by c4_req=-2.945",
    mass_from_claimed_req,
    M_H_PDG,
    abs_tol=SIGMA_H / 10,
    detail="Expected fail: c4=-2.945 gives about 125.088 GeV, not the 125.20 GeV central value.",
)
v.check(
    "central c4 gap from P101 c4 to PDG target",
    c4_req_central - c4_p101,
    0.015,
    rel=5e-2,
    detail="Expected fail: the true central gap is about +0.769; +0.015 is the gap to the paper's lower-edge target.",
)
v.check(
    "mass shift from dc4=+0.015",
    dm_dc4 * dc4_claimed_gap,
    0.0007,
    rel=1e-1,
    detail="Expected fail: derivative gives about +0.0022 GeV; the arithmetic printed in the remark is not reproduced.",
)
v.check("dm_H/dc4 at P101 point", dm_dc4, 0.149, rel=5e-3)

# Topology (b) and NNNLO.
c4b_bound = (4 / 5) ** 2 / 10
c4b_naive = (1 / 2) ** 2 / 10
v.check("topology b upper estimate", c4b_bound, 0.064, rel=1e-12)
v.check("topology b ratio to |c4c|", c4b_bound / abs(c4c), 0.018, rel=2e-2)
v.check("topology b naive formula (1/2)^2/10", c4b_naive, 1 / 40, rel=1e-12)
v.check(
    "topology b naive formula supports +0.015",
    c4b_naive,
    0.015,
    rel=5e-2,
    detail="Expected fail: the displayed naive formula gives +0.025, not +0.015.",
)
v.check("P101 arithmetic -2.960 + 0.015", c4_p101 + 0.015, -2.945, rel=1e-12)
v.check(
    "c4b=+0.015 gives exact PDG central closure",
    higgs_mass(c4_p101 + 0.015),
    M_H_PDG,
    abs_tol=SIGMA_H / 10,
    detail="Expected fail: it gives about 125.088 GeV because -2.945 is not the central target.",
)

dm_dc6 = (V_EW / 2) * LAM6 / (2 * math.sqrt(radicand))
c6_req_central = (target_factor - (1 + 4 * LAM2 / 5 + c4_p101 * LAM4)) / LAM6
v.check(
    "mass shift per unit c6",
    dm_dc6,
    0.015,
    rel=5e-2,
    detail="Expected fail: the square-root derivative gives about 0.00735 GeV per c6; 0.015 omits the 1/(2 sqrt(radicand)) factor.",
)
v.check(
    "c6 needed to close central residual",
    c6_req_central,
    7.0,
    rel=1e-1,
    detail="Expected fail: exact central closure from the P101 point requires c6 about +15.5.",
)

sys.exit(v.summary())
