#!/usr/bin/env python3
"""
verify_P102.py -- Addendum 102: final NNLO Higgs closure.

This verifier checks the nested-loop coefficient, the full c4 arithmetic, the
Higgs mass prediction, and the target/tolerance logic. The final mass value is
reproducible, but the claimed PDG-required c4 target is not the central-value
closure coefficient for m_H = 125.20 GeV; it corresponds approximately to the
lower edge of the 1-sigma band.
"""

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 output adapter: tolerance logic byte-identical to
    verify_common.Verifier.check; emits the modern corpus line format
    ("  [PASS] {n:>2}. {desc}") with computed/claimed/tolerance values
    kept as indented info lines, and the modern RESULT footer."""

    def __init__(self, name: str):
        self.name = name
        self.results = []
        self._n = 0
        print(name)

    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 = abs(computed - claimed)
            err_detail = f"abs err={err:.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}%"
        return self._emit(label, ok, computed, claimed, err_detail, detail)

    def record(self, label, ok, computed="", claimed="", detail=""):
        return self._emit(label, ok, computed, claimed, "", detail)

    def _emit(self, label, ok, computed, claimed, info, ann):
        full_detail = (info + (f"; {ann}" if ann else "")) if info else ann
        self.results.append(CheckResult(label, ok, computed, claimed, full_detail))
        self._n += 1
        desc = f"{label} -- {ann}" if ann else label
        print(f"  [{'PASS' if ok else 'FAIL'}] {self._n:>2}. {desc}")
        if computed != "" or claimed != "":
            print(f"        computed: {computed}")
            print(f"        claimed : {claimed}")
        if info:
            print(f"        {info}")
        return ok

    def summary(self):
        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("P102 -- Final NNLO Higgs Closure")

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

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 = LAM**4


def higgs_mass_from_c4(c4: float) -> float:
    return (V_EW / 2) * math.sqrt(1 + 4 * LAM2 / 5 + c4 * LAM4)


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("4 lambda^2 / 5", 4 * LAM2 / 5, 0.039613, rel=2e-5)

c4a = 16 / 25
c4b = 1 / 40
c4c = -18 / 5
c4_total = c4a + c4b + c4c
v.check("topology a c4", c4a, 0.640, rel=1e-12)
v.check("topology b c4 from claimed N=10", (1 / 16) * (4 / 10), 1 / 40, rel=1e-12)
v.check("topology c c4", c4c, -3.600, rel=1e-12)
v.check("full c4 = 16/25 + 1/40 - 18/5", c4_total, -587 / 200, rel=1e-12)
v.check("full c4 decimal", c4_total, -2.935, rel=1e-12)
v.check("gap to paper c4_req=-2.945", abs(c4_total - (-2.945)), 0.010, rel=1e-12)

radicand = 1 + 4 * LAM2 / 5 + c4_total * LAM4
mass = higgs_mass_from_c4(c4_total)
v.check("NNLO radicand", radicand, 1.032417, rel=1e-5)
v.check("sqrt radicand", math.sqrt(radicand), 1.016081, rel=5e-6)
v.check("NNLO Higgs mass", mass, 125.09, abs_tol=0.005)
v.check("NNLO residual GeV", mass - M_H_PDG, -0.11, abs_tol=0.002)
v.check("NNLO residual sigma", (mass - M_H_PDG) / SIGMA_H, -1.0, rel=1e-2)
v.check("NNLO residual percent", rel_pct(mass, M_H_PDG), -0.09, rel=2e-2)
v.record(
    "exact NNLO 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.00052 GeV below the lower edge; rounded 125.09 is on the edge.",
)

mass_p101 = higgs_mass_from_c4(-74 / 25)
v.check("P101 a+c radicand", 1 + 4 * LAM2 / 5 - 74 * LAM4 / 25, 1.032356, rel=5e-6)
v.check("P101 a+c mass", mass_p101, 125.09, abs_tol=0.01)
v.check("P102 mass shift from topology b", mass - mass_p101, 0.004, abs_tol=0.001)
v.check(
    "radicand shift from topology b is zero",
    c4b * LAM4,
    0.0,
    abs_tol=1e-8,
    detail="Expected fail: including c4b=1/40 shifts the radicand by about 6.13e-5; the later text also states this correctly.",
)

# PDG target coefficient and tolerance logic.
target_factor_central = (2 * M_H_PDG / V_EW) ** 2
c4_req_central = (target_factor_central - (1 + 4 * LAM2 / 5)) / LAM4
mass_from_paper_req = higgs_mass_from_c4(-2.945)
v.check(
    "PDG central target factor (2m/v)^2",
    target_factor_central,
    1.03239,
    rel=5e-5,
    detail="Expected fail: 125.20 GeV gives about 1.03424; 1.03239 corresponds to a mass near 125.088 GeV.",
)
v.check(
    "c4 required for PDG central mass",
    c4_req_central,
    -2.945,
    rel=5e-3,
    detail="Expected fail: exact central closure requires c4 about -2.19 in the signed convention used here.",
)
v.check(
    "mass produced by paper c4_req=-2.945",
    mass_from_paper_req,
    M_H_PDG,
    abs_tol=SIGMA_H / 10,
    detail="Expected fail: c4=-2.945 gives about 125.088 GeV, the lower edge of the 1-sigma band, not the 125.20 central value.",
)
v.check(
    "central c4b gap after a+c",
    c4_req_central - (c4a + c4c),
    0.015,
    rel=5e-2,
    detail="Expected fail: using the true central c4 target, the b-gap is about +0.77, not +0.015.",
)
dm_dc4 = (V_EW / 2) * LAM4 / (2 * math.sqrt(radicand))
v.check("dm_H/dc4 magnitude", dm_dc4, 0.149, rel=5e-3)
v.check(
    "c4 tolerance from sigma_H",
    SIGMA_H / dm_dc4,
    0.3,
    rel=5e-2,
    detail="Expected fail: the derivative gives a 1-sigma c4 tolerance about 0.74; 0.3 is a stricter heuristic, not the value from +/-0.11 GeV.",
)

# Orbit-factor proof checks.
v.check(
    "generic G2 pair orbit dimension from SU(2) stabilizer",
    14 - 3,
    10,
    rel=1e-12,
    detail="Expected fail: the actual orbit dimension is 11 before the paper's extra normalization subtraction.",
)
v.check(
    "topology b c4 using raw orbit dimension 11",
    (1 / 16) * (4 / 11),
    1 / 40,
    rel=1e-3,
    detail="Expected fail: without the ad hoc 11->10 subtraction, c4b would be 1/44.",
)
v.record(
    "orbit-dimension theorem does not equate 14-3 with 11-1",
    "14 - 3 = 11 - 1 = 10" not in TEX,
    "paper writes 14 - 3 = 11 - 1 = 10",
    "14 - 3 = 11",
    "Expected fail: the pure orbit dimension is 11; the additional normalization step is a separate convention and needs proof.",
)
v.record(
    "comparison with P101 has no zero-shift wording",
    "+0.0071960 - 0.0071960 = 0" not in TEX,
    "paper says topology b shifts the radicand by +0.0071960 - 0.0071960 = 0",
    "shift = c4b*lambda^4",
    "Expected fail: the actual P101->P102 radicand shift is small but nonzero, about 0.000061.",
)

sys.exit(v.summary())
