#!/usr/bin/env python3
"""
verify_P049.py -- Addendum 49: W/Z masses from E6 adjoint sector.

This verifier checks the Killing-form arithmetic, Weinberg-angle ratio,
VEV cross-check, and W/Z closure table in 49_Addendum_WZMasses.tex.  Most
headline numerics reproduce and the paper correctly leaves the absolute W mass
open.  The flagged issues are a stale M_Z-from-M_W table value, an unverified
"systematic scan" claim, a speculative RG attribution, and a TeX/math notation
bug where \\sinW is defined as sin^2(theta_W) but used as sin(theta_W) in mixing
generator formulas.
"""

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("P049 -- W/Z Masses from E6 Adjoint")

ROOT = Path(__file__).resolve().parents[1]
TEX = (ROOT / "49_Addendum_WZMasses.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
ME_GEV = 0.000511
MW = 80.377
MZ = 91.188
MH = 125.25
V_SM = 246.22


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


sin2_toe = 1 / (1 + PI)
cos_toe = math.sqrt(PI / (1 + PI))
lambda_h = 9 * PI**2 / (5 * MU0)
v_from_higgs = MH / math.sqrt(2 * lambda_h)
g_toe2 = 4 * PI * (1 + PI) / MU0
g_toe = math.sqrt(g_toe2)
g_sm = 2 * MW / v_from_higgs
ew_killing = PI + math.log(12) / MU
mw_killing_mev = ME_GEV * math.exp(MU * (ew_killing - PI)) * 1000
ew_obs = PI + math.log(MW / ME_GEV) / MU


v.check("mu0", MU0, 137.036, rel=3e-6)
v.check("mu1", MU1, 108.717, rel=5e-6)
v.check("MU", MU, 0.79334, rel=3e-6)
v.check("lambda_H=9pi^2/(5mu0)", lambda_h, 0.12964, rel=5e-5)
v.check("sin^2 theta_W TOE", sin2_toe, 0.2415, rel=2e-4)
v.check("cos theta_W TOE", cos_toe, 0.8709, rel=6e-5)

v.check("Killing contribution total", 3 + 9 / 2 + 9 / 2, 12, rel=1e-12)
v.check("Killing energy pi+ln(12)/MU", ew_killing, 6.27, rel=7e-4)
v.check("Killing mass scale", mw_killing_mev, 6.0, rel=3e-2)
v.check("observed W energy", ew_obs, 18.22, rel=3e-4)

ratio_toe = 1 / cos_toe
ratio_obs = MZ / MW
v.check("mZ/mW TOE ratio", ratio_toe, 1.1482, rel=3e-5)
v.check("observed mZ/mW ratio", ratio_obs, 1.1345, rel=4e-6)
v.check("mZ/mW residual percent", pct(ratio_toe, ratio_obs), 1.21, rel=5e-3)
v.check("mW from mZ and TOE theta", MZ * cos_toe, 79.42, rel=5e-5)
v.check("mW-from-mZ residual", pct(MZ * cos_toe, MW), -1.19, rel=1e-2)
v.check(
    "mZ from mW and TOE theta table row",
    MW / cos_toe,
    91.09,
    rel=5e-4,
    detail="Expected fail: using observed mW and TOE theta gives about 92.29 GeV, not 91.09.",
)
v.check(
    "mZ-from-mW residual table row",
    pct(MW / cos_toe, MZ),
    1.1,
    rel=5e-2,
    detail="Expected fail: exact residual is about +1.21%, and the listed 91.09 is stale.",
)

v.check("VEV from Higgs self-coupling and observed mH", v_from_higgs, 245.98, rel=2e-5)
v.check("VEV residual percent", pct(v_from_higgs, V_SM), -0.10, rel=2e-2)
v.check("g_SM from observed W and computed v", g_sm, 0.6535, rel=6e-5)
v.check("g_TOE^2 candidate", g_toe2, 0.3798, rel=4e-5)
v.check("g_TOE candidate", g_toe, 0.6163, rel=5e-5)
v.check("mW from g_TOE and v", g_toe * v_from_higgs / 2, 75.79, rel=7e-5)
v.check("mW g_TOE residual", pct(g_toe * v_from_higgs / 2, MW), -5.7, rel=4e-3)

v.record(
    "systematic no-match scan is reproducible from the paper",
    False,
    computed="paper states a systematic scan but gives no candidate set, code, or result table",
    claimed="no algebraic combination maps Killing norm to E_W within 5%",
    detail="Expected verification gap.",
)
v.record(
    "5.7 percent g deficit is derived from a TOE RG calculation",
    False,
    computed="paper gives only an order-of-magnitude one-loop estimate with typical GUT parameters",
    claimed="deficit attributable to RG running",
    detail="Expected status fail: plausible interpretation, not a computed derivation.",
)
v.record(
    "mixing generator formulas use sin(theta), not sin^2(theta)",
    "\\newcommand{\\sinW}{\\sin^2\\!\\theta_W}" not in TEX or "Z^0 = \\cosW\\, W^3 - \\sinW\\, B" not in TEX,
    computed="\\sinW macro is sin^2(theta_W), but Z^0 and photon generator formulas use \\sinW as a linear mixing coefficient",
    claimed="Z^0 = cos(theta) W^3 - sin(theta) B",
    detail="Expected notation/formula fail.",
)
v.record(
    "absolute W mass is explicitly open",
    "Conjecture 7.1 & \\textbf{Open (refined)}" in TEX and "$m_W$ absolute: requires RG calculation" in TEX,
    computed="status table leaves absolute mass open",
    claimed="ratio closed; absolute scale open",
)

sys.exit(v.summary())
