#!/usr/bin/env python3
"""
verify_P089.py -- Addendum 89: Electroweak VEV from Jordan coupling.

This verifier checks the VEV arithmetic in 89_Addendum_ElectroweakVEV.tex.
The leading-order identity v=2*mH0 and the NLO cancellation algebra reproduce.
The flagged issues are narrower internal/status problems: the boxed structural
formula has an extra factor of 2 under the square root, the all-order protection
claim is conditional on an assumed common loop factor, and the text alternates
between closing W/Z absolute masses and leaving g_W as an open input.
"""

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):
    """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("P089 -- Electroweak VEV from Jordan Coupling")

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

PI = math.pi
MU0 = 4 * PI**3 + PI**2 + PI
LAM = math.sin(PI / 14)
KAPPA = 1 + 4 * LAM**2 / 5
N_GEN = 3
HVE_E6 = 12
LAMBDA_H0 = N_GEN / (2 * HVE_E6)
MH0 = 123.11
MH_EXP = 125.20
V_PDG = 246.22
SIN2W_NLO = 0.23192
COS2W_NLO = 1 - SIN2W_NLO


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


v.check("mu0", MU0, 137.036, rel=3e-6)
v.check("lambda=sin(pi/14)", LAM, 0.22252, rel=5e-5)
v.check("lambda^2", LAM**2, 0.049516, rel=9e-6)
v.check("4 lambda^2 / 5", 4 * LAM**2 / 5, 0.039613, rel=2e-5)
v.check("lambda_H0=N_gen/(2 hvee)", LAMBDA_H0, 1 / 8, rel=1e-12)
v.check("sqrt(2 lambda_H0)", math.sqrt(2 * LAMBDA_H0), 0.5, rel=1e-12)
v.check("LO VEV 2*mH0", 2 * MH0, 246.22, rel=1e-12)
v.check("LO VEV from mH/sqrt(2lambda)", MH0 / math.sqrt(2 * LAMBDA_H0), 246.22, rel=1e-12)
v.check("LO mH residual", pct(MH0, MH_EXP), -1.67, rel=8e-4)

lambda_h1 = LAMBDA_H0 * KAPPA
mh1 = MH0 * math.sqrt(KAPPA)
v.check("NLO lambda_H", lambda_h1, 0.12995, rel=2e-5)
v.check("NLO Higgs mass", mh1, 125.53, rel=5e-5)
v.check("NLO Higgs residual", pct(mh1, MH_EXP), 0.26, rel=4e-3)
v.check("NLO VEV cancellation", mh1 / math.sqrt(2 * lambda_h1), V_PDG, rel=1e-12)
v.check("SM lambda_H from PDG mH and v", MH_EXP**2 / (2 * V_PDG**2), 0.1293, rel=2e-4)
v.check("correct Coxeter factor sqrt(hvee/Ngen)", math.sqrt(HVE_E6 / N_GEN), 2.0, rel=1e-12)

boxed_factor = math.sqrt(2 * HVE_E6 / N_GEN)
v.check(
    "boxed structural factor sqrt(2*hvee/Ngen)",
    boxed_factor,
    2.0,
    rel=1e-12,
    detail="Expected fail: the boxed formula includes an extra factor of 2; sqrt(2*12/3)=sqrt(8), not 2.",
)
v.check(
    "boxed structural formula numerical VEV",
    boxed_factor * MH0,
    246.22,
    rel=1e-3,
    detail="Expected fail: the boxed formula would give about 348.21 GeV.",
)

mz_without_gauge = V_PDG / (2 * math.sqrt(SIN2W_NLO) * math.sqrt(COS2W_NLO))
v.check("MZ formula without gauge coupling", mz_without_gauge, 291.8, rel=5e-4)
v.record(
    "W/Z absolute masses are closed in this addendum",
    "OPEN: Derive $g_W$" not in TEX,
    computed="text explicitly leaves g_W, M_W, and M_Z absolute prediction open",
    claimed="Section title/abstract language says W and Z absolute masses are closed",
    detail="Expected status fail: P89 closes the VEV piece, not the gauge-coupling magnitude.",
)
v.record(
    "all-order VEV protection is unconditional",
    "provided the loop correction to $m_H^2$ is the same multiplicative factor" not in TEX,
    computed="corollary states the all-order result only if the same kappa_n multiplies mH^2 and lambda_H",
    claimed="loop-exact at all orders",
    detail="Expected proof-status fail: the all-order statement is conditional on a shared loop factor.",
)

frac_bdy_total = PI**2 / MU0
g_from_conj = math.sqrt(4 * PI * frac_bdy_total / (1 - frac_bdy_total))
v.check(
    "conjectured g_W from natural boundary fraction",
    g_from_conj,
    0.653,
    rel=2e-2,
    detail="Expected fail under the natural FRAC_bdy=pi^2/mu0 reading; the deferred formula gives g_W≈0.988, not 0.653.",
)
v.record(
    "g_W formula is proved here",
    "Proof deferred to Addendum~90" not in TEX,
    computed="P89 labels the g_W expression as a conjecture and defers proof",
    claimed="absolute boson masses derived",
    detail="Expected status fail.",
)

sys.exit(v.summary())
