#!/usr/bin/env python3
"""
verify_P039.py -- Addendum 39: Higgs sector identification.

This verifier checks the Higgs-sector arithmetic in
39_Addendum_HiggsIdentification.tex: rho moments, layer fractions, tree
Weinberg/MW-MZ ratio, the proposed Higgs self-coupling, Higgs mass from v,
and the v=e*MZ estimate. It also checks two representation-consistency
claims that can be tested at the level of the stated subspaces.

The main flags are: the Higgs mass/SM-lambda comparison is stale under the
paper's own v=246.22 input; the proof text assigns the lower Higgs component
Y=-1/2 before the table assigns both Higgs components Y=+1/2; and the J3(O)
slice (<e0,x13>, <e7,x23>) is not invariant under a generic row-index SU(2)
rotation.
"""

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 Verifier as _BaseVerifier, CheckResult


class Verifier(_BaseVerifier):
    """Output-layer normalization only: same checks, modern [PASS]/[FAIL] 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)
        note, info = "", detail
        if not ok and "Expected" in detail:
            i = detail.find("Expected")
            note = " -- " + detail[i:]
            info = detail[:i].rstrip().rstrip(";")
        print(f"  [{'PASS' if ok else 'FAIL'}] {n:>2}. {label}{note}")
        if computed != "" or claimed != "":
            print(f"        computed: {computed}")
            print(f"        claimed : {claimed}")
        if info:
            print(f"        {info}")
        return ok

    def summary(self):
        passed = sum(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 = Verifier("P039 -- Higgs Sector Identification")

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

PI = math.pi
MU0 = 4.0 * PI**3 + PI**2 + PI
MU1 = 16.0 * PI**3 / 5.0 + 3.0 * PI**2 / 4.0 + 2.0 * PI / 3.0
MU = MU1 / MU0
V_EW = 246.22
M_H_OBS = 125.11
M_H_SIGMA = 0.11
M_Z = 91.19


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


frac_bdy = PI**2 / MU0
frac_edge = PI / MU0
frac_bulk = 4.0 * PI**3 / MU0
lambda_toe = 9.0 * PI**2 / (5.0 * MU0)
lambda_sm = M_H_OBS**2 / (2.0 * V_EW**2)
m_h_toe = math.sqrt(2.0 * lambda_toe) * V_EW

v.check("mu0", MU0, 137.036, rel=3e-6)
v.check("mu1", MU1, 108.717, rel=3e-6)
v.check("MU", MU, 0.7933, rel=6e-5)
v.check("boundary fraction", frac_bdy, 0.07202, rel=3e-4)
v.check("layer fractions sum to unity", frac_bdy + frac_edge + frac_bulk, 1.0, rel=1e-12)
v.check("C tensor O dimension split", 1 + 1 + 3 + 3, 8, rel=1e-12)

sin2_tree = 1.0 / (1.0 + PI)
mw_mz_toe = math.sqrt(PI / (1.0 + PI))
mw_mz_obs = 80.377 / 91.1876
v.check("tree sin^2 theta_W", sin2_tree, 0.2414, rel=3e-4)
v.check("MW/MZ tree ratio", mw_mz_toe, 0.8709, rel=6e-5)
v.check("MW/MZ residual percent", pct(mw_mz_toe, mw_mz_obs), -1.19, rel=2e-3)
v.check(
    "tree Weinberg deviation from 0.2312",
    pct(sin2_tree, 0.2312),
    4.24,
    rel=5e-3,
    detail="Expected fail: using the paper's stated 0.2312 comparator gives about +4.43%; +4.24% uses a different comparator.",
)

v.check("lambda_H TOE", lambda_toe, 0.12964, rel=8e-6)
v.check(
    "lambda_H SM from 125.11 and 246.22",
    lambda_sm,
    0.12933,
    rel=5e-4,
    detail="Expected fail: the displayed inputs give about 0.12909, not 0.12933.",
)
v.check(
    "lambda_H error percent",
    pct(lambda_toe, lambda_sm),
    0.24,
    rel=5e-2,
    detail="Expected fail: with M_H=125.11 and v=246.22 the error is about +0.42%.",
)
v.check(
    "Higgs mass from lambda_H and v=246.22",
    m_h_toe,
    125.26,
    rel=2e-4,
    detail="Expected fail: exact substitution gives about 125.37 GeV.",
)
v.check(
    "Higgs mass residual percent",
    pct(m_h_toe, M_H_OBS),
    0.12,
    rel=6e-2,
    detail="Expected fail: exact substitution gives about +0.21%.",
)
v.check(
    "Higgs mass sigma offset",
    (m_h_toe - M_H_OBS) / M_H_SIGMA,
    1.4,
    rel=5e-2,
    detail="Expected fail: exact substitution gives about 2.4 sigma for the stated 0.11 GeV uncertainty.",
)

v.check("v = e*MZ candidate", math.e * M_Z, 247.9, rel=2e-4)
v.check("v=e*MZ residual percent", pct(math.e * M_Z, V_EW), 0.7, rel=5e-2)
v.check("spectral gap ln(v/MZ)/MU", math.log(V_EW / M_Z) / MU, 1.0 / MU, rel=7e-3)

v.record(
    "Higgs proof assigns common hypercharge +1/2 to both doublet components",
    "Y = -\\tfrac{1}{2}$ on the lower component" not in TEX,
    computed="proof text says lower e7 component has Y=-1/2, while the table assigns e7 in the Higgs doublet Y=+1/2",
    claimed="Higgs doublet (1,2,+1/2)",
    detail="Expected representation-consistency fail: an SM Higgs doublet has common hypercharge +1/2 across both isospin components.",
)

v.record(
    "J3 Higgs slice is invariant under row-index SU(2)",
    False,
    computed="the rotation (x13,x23)->(x23,-x13) maps (a*e0 in x13, b*e7 in x23) to (b*e7 in x13, -a*e0 in x23), outside the stated slice (e0 in x13, e7 in x23)",
    claimed="V_H^{J3} is a row-index SU(2) doublet",
    detail="Expected representation-consistency fail unless the selected singlet basis is enlarged or the SU(2) action also rotates e0<->e7.",
)

v.record(
    "lambda_H is derived rather than conjectural",
    "\\begin{conjecture}[Higgs self-coupling]" not in TEX,
    computed="paper labels lambda_H as a conjecture and leaves its derivation to OP2/Phase 4",
    claimed="Higgs self-coupling identification",
    detail="Expected status note.",
)

sys.exit(v.summary())
