#!/usr/bin/env python3
"""
verify_P097.py -- Addendum 97: Higgs NNLO Jordan loop correction.

This verifier checks the NNLO Higgs coefficient arithmetic and selected
Jordan-algebra proof claims in 97_Addendum_HiggsNNLO.tex.

The NLO mass and the additive topology-(a) mass arithmetic reproduce. The
flagged issues are the central c4 target, the one-sigma c4 band, the internal
inconsistency between the displayed required-c4 formula and the later compact
formula, the double-insertion bookkeeping, and proof-status claims about the
Jordan associator and orbit dimensions.
"""

from __future__ import annotations

import math
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
class Verifier:
    """Output shim: identical tolerance semantics to verify_common.Verifier,
    modern [PASS]/[FAIL] check-line output format."""

    def __init__(self, name):
        self.PASS = 0
        self.FAIL = 0
        self.n = 0
        print(name)

    def _mark(self, ok, desc):
        self.n += 1
        if ok:
            self.PASS += 1
        else:
            self.FAIL += 1
        print(f"  [{'PASS' if ok else 'FAIL'}] {self.n:>2}. {desc}")

    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}%"
        self._mark(ok, label + (f" -- {detail}" if detail else ""))
        print(f"        computed: {computed}   claimed: {claimed}   ({err_detail})")
        return ok

    def record(self, label, ok, computed="", claimed="", detail=""):
        ok = bool(ok)
        self._mark(ok, label + (f" -- {detail}" if detail else ""))
        if computed != "" or claimed != "":
            print(f"        computed: {computed}   claimed: {claimed}")
        return ok

    def summary(self):
        print(f"\n{'='*60}\nRESULT: {self.PASS} PASS / {self.FAIL} FAIL")
        return 0 if self.FAIL == 0 else 1


v = Verifier("P097 -- Higgs NNLO Jordan Loop")

V_EW = 246.22
M_H = 125.20
SIGMA_H = 0.11
LAM = math.sin(math.pi / 14)
LAM2 = LAM**2
LAM4 = LAM2**2
XI = 4 * LAM2 / 5
C4_A = 16 / 25


def mass_from_c4(c4: float) -> float:
    return (V_EW / 2) * math.sqrt(1 + XI + c4 * LAM4)


def c4_for_mass(mass: float) -> float:
    return ((2 * mass / V_EW) ** 2 - (1 + XI)) / LAM4


def jordan(a, b):
    def matmul(x, y):
        return [
            [sum(x[i][k] * y[k][j] for k in range(3)) for j in range(3)]
            for i in range(3)
        ]

    ab = matmul(a, b)
    ba = matmul(b, a)
    return [[0.5 * (ab[i][j] + ba[i][j]) for j in range(3)] for i in range(3)]


def sub(a, b):
    return [[a[i][j] - b[i][j] for j in range(3)] for i in range(3)]


def assoc(a, b, c):
    return sub(jordan(jordan(a, b), c), jordan(a, jordan(b, c)))


def sym(i: int, j: int):
    m = [[0.0 for _ in range(3)] for _ in range(3)]
    m[i][j] = 1.0
    m[j][i] = 1.0
    return m


def diag_entries(m):
    return tuple(m[i][i] for i in range(3))


target_factor = (2 * M_H / V_EW) ** 2
c4_req_central = c4_for_mass(M_H)
c4_req_lower = c4_for_mass(M_H - SIGMA_H)
c4_req_upper = c4_for_mass(M_H + SIGMA_H)
c4_prop_display = -(5 / (4 * LAM4)) * (XI + 1 - target_factor)
c4_from_stale_factor = (1.03239 - (1 + XI)) / LAM4
m_lo = V_EW / 2
m_nlo = m_lo * math.sqrt(1 + XI)
m_topo_a_additive = mass_from_c4(C4_A)
m_topo_a_squared = m_lo * (1 + XI)

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-6)
v.check("4 lambda^2 / 5", XI, 0.039613, rel=2e-5)
v.check("LO Higgs mass v/2", m_lo, 123.11, rel=5e-5)
v.check("NLO Higgs mass", m_nlo, 125.53, rel=5e-5)
v.check("NLO residual GeV", m_nlo - M_H, 0.33, rel=2e-2)
v.check("NLO residual sigma", (m_nlo - M_H) / SIGMA_H, 3.0, rel=2e-2)
v.check("lambda^4 natural band percent", 100 * LAM4, 0.245, rel=1e-3)

v.check(
    "central c4 required for m_H=125.20",
    c4_req_central,
    -2.945,
    rel=1e-3,
    detail="Expected fail: -2.945 closes the lower one-sigma edge, not the central mass.",
)
v.check(
    "target factor (2m/v)^2",
    target_factor,
    1.03239,
    rel=1e-5,
    detail="Expected fail: 2*125.20/246.22 squared is about 1.03424.",
)
v.check(
    "displayed proposition c4 formula with -5/(4 lambda^4)",
    c4_prop_display,
    -1.069,
    rel=1e-3,
    detail="Expected fail: the displayed formula evaluates to about -2.74 with central inputs and has an extra 5/4 factor relative to the compact formula.",
)
v.check(
    "stale proof arithmetic c4 from 1.03239",
    c4_from_stale_factor,
    -2.945,
    rel=1e-3,
    detail="This reproduces the paper's -2.945 value when the stale target factor 1.03239 is used.",
)
v.check("c4=-2.945 mass", mass_from_c4(-2.945), 125.09, rel=2e-5)
v.check(
    "central-closure mass from printed c4=-2.945",
    mass_from_c4(-2.945),
    M_H,
    abs_tol=0.01,
    detail="Expected fail: this coefficient gives about 125.09 GeV, not 125.20 GeV.",
)
v.check(
    "one-sigma lower-edge c4",
    c4_req_lower,
    -3.26,
    rel=1e-2,
    detail="Expected fail: exact lower-edge c4 is about -2.93.",
)
v.check(
    "one-sigma upper-edge c4",
    c4_req_upper,
    -2.62,
    rel=1e-2,
    detail="Expected fail: exact upper-edge c4 is about -1.45.",
)
v.check(
    "c4 uncertainty from +/-0.11 GeV",
    (c4_req_upper - c4_req_lower) / 2,
    0.3,
    rel=1e-2,
    detail="Expected fail: the stated mass uncertainty corresponds to about +/-0.74 in c4.",
)

v.check("topology-a c4 = 16/25", C4_A, 0.6400, rel=1e-12)
v.check("topology-a additive mass", m_topo_a_additive, 125.62, rel=5e-5)
v.check(
    "topology-a multiplicative proof mass",
    m_topo_a_squared,
    125.62,
    rel=5e-4,
    detail="Expected fail: the proof expands (1+xi)^2, which doubles the O(lambda^2) term and would give about 127.99 GeV if taken literally.",
)
v.check(
    "NLO correction formula from printed loop eigenvalue",
    (-2) * (-1 / 4) * LAM2 / 5,
    XI,
    rel=1e-12,
    detail="Expected fail: with Sigma_H=lambda^2 and N_H=5 the printed formula gives lambda^2/10, not 4lambda^2/5.",
)

v.check(
    "(b)+(c) needed for central PDG closure after topology-a",
    c4_req_central - C4_A,
    -3.585,
    rel=1e-3,
    detail="Expected fail: -3.585 is based on the lower-edge/stale c4 target; central closure needs about -2.831.",
)
v.check(
    "one-sigma c4 interval lower endpoint printed",
    min(c4_req_lower, c4_req_upper),
    -3.26,
    rel=1e-2,
    detail="Expected fail: exact 1-sigma interval is roughly [-2.93, -1.45].",
)
v.check(
    "one-sigma c4 interval upper endpoint printed",
    max(c4_req_lower, c4_req_upper),
    -2.62,
    rel=1e-2,
    detail="Expected fail: exact 1-sigma interval is roughly [-2.93, -1.45].",
)

abc = assoc(sym(0, 1), sym(1, 2), sym(2, 0))
acb = assoc(sym(0, 1), sym(2, 0), sym(1, 2))
cba = assoc(sym(2, 0), sym(1, 2), sym(0, 1))
v.record(
    "raw associator sign matches stated theorem",
    False,
    computed="the proof's own Step 5 gives +1/4(E33-E22), i.e. -1/4(E22-E33)",
    claimed="+1/4(E22-E33)",
    detail="Expected proof-audit fail: changing sign by convention conflicts with the fixed associator definition.",
)
v.record(
    "nonzero Peirce associator requires octonion non-associativity",
    False,
    computed=f"real symmetric Jordan matrices already give nonzero diagonal associator {diag_entries(abc)} up to normalization",
    claimed="nonzero result is a direct consequence of non-associativity of O",
    detail="Expected proof-audit fail: the same Peirce-index associator is nonzero in special Jordan matrix algebras.",
)
v.record(
    "Jordan associator is antisymmetric in the last two arguments",
    all(abs(abc[i][j] + acb[i][j]) < 1e-12 for i in range(3) for j in range(3)),
    computed=f"ABC diagonal={diag_entries(abc)}, ACB diagonal={diag_entries(acb)}",
    claimed="{A,B,C} = -{A,C,B}",
    detail="Expected proof-audit fail: the standard identity is antisymmetry in the outer variables, not the last two.",
)
v.record(
    "Jordan associator is antisymmetric in the outer variables",
    all(abs(abc[i][j] + cba[i][j]) < 1e-12 for i in range(3) for j in range(3)),
    computed=f"ABC diagonal={diag_entries(abc)}, CBA diagonal={diag_entries(cba)}",
    claimed="{A,B,C} = -{C,B,A}",
)
v.record(
    "nested-loop orbit dimension N_b=10 is derived",
    False,
    computed="the proof first gives dim G2/SU3 = 6, then uses 6+6-2=10 after already restricting to S6 unit directions",
    claimed="N_b=10 derived from G2/P",
    detail="Expected proof-audit fail: the two-parameter subtraction/orbit quotient is not justified.",
)
v.record(
    "status remains open",
    True,
    computed="P97 explicitly states OP-P97-1 and says NNLO is not closed",
    claimed="NNLO not closed",
)

sys.exit(v.summary())
