#!/usr/bin/env python3
"""
verify_P037.py -- Addendum 37: gauge group derivation.

This verifier checks the group/dimension arithmetic in
37_Addendum_GaugeGroup.tex and audits which identifications are proved versus
conjectural.  Many standard dimensions and the Weinberg-angle arithmetic pass.
The flagged issues are mostly proof-status problems, plus two concrete group
facts: Aut(C) as a real algebra is Z2 rather than U(1), and Aut(H) is SO(3)
(equivalently SU(2)/Z2), not SU(2) itself.
"""

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("P037 -- Gauge Group Derivation")

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

PI = math.pi
MU0 = 4 * PI**3 + PI**2 + PI


v.check("mu0 from rho integral", MU0, 137.036, rel=3e-6)
v.check("Hurwitz real dimensions sum endpoint O", 8, 8, rel=1e-12)
v.check("bulk coefficient 16=2dim(O)", 16, 2 * 8, rel=1e-12)
v.check("dim G2", 14, 14, rel=1e-12)
v.check("rank G2", 2, 2, rel=1e-12)
v.check("dim SU(3)", 8, 8, rel=1e-12)
v.check("rank SU(3)", 2, 2, rel=1e-12)
v.check("coset dimension G2/SU3", 14 - 8, 6, rel=1e-12)
v.check("dim SU(2)", 3, 3, rel=1e-12)
v.check("dim U(1)", 1, 1, rel=1e-12)

v.record(
    "Aut(C) is U(1) as an R-algebra automorphism group",
    False,
    computed="Aut_R(C) has two elements: identity and complex conjugation",
    claimed="Aut(C) superset/equals U(1) in the gauge chain table",
    detail="Expected group-fact fail: U(1) is the unit group / Hopf structure group, not the algebra automorphism group.",
)
v.record(
    "Aut(H) is SU(2) exactly",
    False,
    computed="unit quaternions SU(2) act by conjugation with kernel {+/-1}, giving Aut(H)=SO(3)=SU(2)/Z2",
    claimed="Aut(H)=SU(2)",
    detail="Expected group-fact fail.",
)

sin2_tree = 1.0 / (1.0 + 3.0)
sin2_full = 1.0 / (1.0 + 3.0 + 8.0)
sin2_sector = PI / (PI + PI**2)
v.check("tree Weinberg angle from dim count", sin2_tree, 0.25, rel=1e-12)
v.check("full U1+SU2+SU3 dimension count", sin2_full, 1.0 / 12.0, rel=1e-12)
v.check("sector energy ratio Ee/Emu", PI / PI**2, 1.0 / PI, rel=1e-12)
v.check("sector energy ratio Ee/Ebulk", PI / (4.0 * PI**3), 1.0 / (4.0 * PI**2), rel=1e-12)
v.check("Weinberg sector-energy conjecture value", sin2_sector, 0.241, rel=2e-3)

v.check("J3(O) dimension", 3 + 3 * 8, 27, rel=1e-12)
v.check("J3(O) diagonal generation slots", 3, 3, rel=1e-12)
v.check("J3(O) off-diagonal octonion components", 3 * 8, 24, rel=1e-12)

gamma_shift = (9.0 / 16.0) / (PI**2 - PI)
muon_total = 7.0e-4 + 4.3e-3 + gamma_shift
lambda_mu = PI**2 / (PI + PI**2)
v.check("muon gamma T second-order term", gamma_shift, 0.0836, rel=5e-4)
v.check("muon perturbative total", muon_total, 0.089, rel=5e-3)
v.check("muon fixed-point lambda", lambda_mu, 0.759, rel=6e-4)

v.record(
    "SU(2)_L rather than SU(2)_R follows from S3 orientation alone",
    False,
    computed="orientation distinguishes left/right conventions, but physical weak chirality is an additional identification",
    claimed="TOE boundary carries SU(2)_L and not SU(2)_R",
    detail="Expected proof-status fail.",
)
v.record(
    "Hopf U(1) is proved to be hypercharge rather than a generic fiber phase",
    False,
    computed="Hopf bundle proves a U(1) structure group; identifying it with hypercharge uses the Paper 20 dictionary",
    claimed="U(1)_Y from Hopf fiber is proven",
    detail="Expected physical-identification fail.",
)
v.record(
    "Hurwitz theorem forbids any additional gauge factor",
    False,
    computed="Hurwitz forbids further normed division algebras, not arbitrary additional gauge sectors unless the division-algebra ansatz is assumed complete",
    claimed="no fourth gauge group/layer exists",
    detail="Expected proof-status fail.",
)
v.record(
    "physical color assignment is marked conjectural",
    "Conjecture" in TEX and "SU(3)_c" in TEX and "Needs quark sector" in TEX,
    computed="color assignment status table marks it as conjecture",
    claimed="not fully proved",
)
v.record(
    "off-diagonal 8 real components are SU(3) color generators",
    False,
    computed="under SU(3), O decomposes as 1+1+3+3bar; quark colors live in 3/3bar, while 8 generators are the adjoint Lie algebra",
    claimed="8-dimensional x_ij is natural carrier of 8 color generators",
    detail="Expected representation-theory fail.",
)
v.record(
    "complete J3(O) Standard Model decomposition is proved here",
    "Conjecture" not in TEX or "Needs rep theory" not in TEX,
    computed="summary marks full J3(O) SM spectrum as conjecture needing representation theory",
    claimed="J3(O) as master algebra proved",
    detail="Expected status fail.",
)

sys.exit(v.summary())
