#!/usr/bin/env python3
"""
verify_P052.py -- Addendum 52: OP-B-T2 and OP-B-Mass status.

This verifier checks the concrete arithmetic and finite-map logic in
52_Addendum_ConjBClosure.tex: rho moments, Xsec trace, charm energy,
EW sub-density integral, charm mass, top/charm gap, top mass, and the
six-permutation gauge-consistency enumeration.

The arithmetic and the "OP-B-Mass remains open" status are internally
consistent. The flagged issues are wording/proof-scope points: the
idempotent-sector uniqueness is conditional on the imported TOE
gauge-sector identification, not a consequence of the abstract Z3
decomposition alone; the text itself acknowledges that physical input.
The 2% top gap is also attributed to QCD running without computing that
correction in this addendum.
"""

from __future__ import annotations

import itertools
import math
import sys
from pathlib import Path

PASS = FAIL = 0
_N = 0


def check(desc, cond):
    global PASS, FAIL, _N
    _N += 1
    ok = bool(cond)
    PASS += ok
    FAIL += not ok
    print(f"  [{'PASS' if ok else 'FAIL'}] {_N:>2}. {desc}")
    return ok


class Verifier:
    """Same check semantics as verify_common.Verifier; modern output style."""

    def __init__(self, name):
        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.record(label, ok, computed, claimed, err_detail + (f"; {detail}" if detail else ""))

    def record(self, label, ok, computed="", claimed="", detail=""):
        check(label + (f" -- {detail}" if detail else ""), ok)
        if computed != "" or claimed != "":
            print(f"        computed: {computed}")
            print(f"        claimed : {claimed}")
        return ok

    def summary(self):
        print(f"\n{'='*60}\nRESULT: {PASS} PASS / {FAIL} FAIL")
        return 1 if FAIL else 0


v = Verifier("P052 -- OP-B-T2 and OP-B-Mass")

ROOT = Path(__file__).resolve().parents[1]
TEX = (ROOT / "52_Addendum_ConjBClosure.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
ME_MEV = 0.51099895

E_E = PI
E_B = PI**2
E_BULK = 4.0 * PI**3
E_C = E_E + E_B
XSEC_TRACE = E_E + E_B + E_BULK
M_C = ME_MEV * math.exp(MU * E_B)
GAP = math.log(MU0) / MU
E_T = E_C + GAP
TOP_CHARM_RATIO = math.exp(MU * GAP)
M_T = ME_MEV * math.exp(MU * (E_T - E_E))
PDG_MC = 1270.0
PDG_MT = 172700.0


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


idempotent_stabilizer = {"e1": "U(1)_Y", "e2": "SU(2)_L", "e3": "G2"}
sector_gauge = {"edge": "U(1)_Y", "boundary": "SU(2)_L", "bulk": "G2"}
canonical = {"e1": "edge", "e2": "boundary", "e3": "bulk"}
consistent = []
for sectors in itertools.permutations(sector_gauge):
    sigma = dict(zip(idempotent_stabilizer, sectors))
    if all(sector_gauge[sigma[e]] == idempotent_stabilizer[e] for e in sigma):
        consistent.append(sigma)

v.check("mu0", MU0, 137.0363, rel=3e-7)
v.check("mu1", MU1, 108.7167, rel=2e-7)
v.check("MU", MU, 0.79334, rel=3e-6)
v.check("sector energy Ee", E_E, PI, rel=1e-12)
v.check("sector energy Eb", E_B, 9.8696, rel=5e-6)
v.check("sector energy EB", E_BULK, 124.0251, rel=1e-6)
v.check("Xsec trace equals mu0", XSEC_TRACE, MU0, rel=1e-12)
v.check("Ec = Ee + Eb", E_C, 13.011, rel=2e-5)
v.check("EW sub-density integral", PI + PI**2, E_C, rel=1e-12)
v.check("charm mass from mass formula", M_C, 1285.0, rel=2e-4)
v.check("charm residual vs 1270 MeV percent", pct(M_C, PDG_MC), 1.0, rel=3e-1)
v.check("ln(mu0)", math.log(MU0), 4.9196, rel=2e-4)
v.check("top-charm energy gap", GAP, 6.2019, rel=5e-6)
v.check("top energy", E_T, 19.213, rel=7e-6)
v.check("top/charm ratio", TOP_CHARM_RATIO, MU0, rel=1e-12)
v.check("top mass MeV", M_T, 176105.0, rel=5e-6)
v.check("top mass residual percent", pct(M_T, PDG_MT), 2.0, rel=2e-2)
v.check("route 1 spectral weight ratio", MU0 / E_C, 10.53, rel=3e-4)
v.record(
    "route 1 does not give the top/charm ratio",
    abs(MU0 / E_C - MU0) > 100.0,
    computed=f"mu0/Ec = {MU0/E_C:.6f}, mu0 = {MU0:.6f}",
    claimed="route 1 gives wrong mass ratio",
)

v.check("number of sector-idempotent bijections", math.factorial(3), 6, rel=0)
v.check("unique gauge-consistent bijection count", len(consistent), 1, rel=0)
v.record(
    "unique bijection is the canonical one",
    consistent == [canonical],
    computed=consistent,
    claimed=canonical,
)
v.record(
    "G2 pointwise-fixes diagonal idempotents under octonion automorphisms",
    True,
    computed="octonion automorphisms act on off-diagonal octonion entries and leave real diagonal entries fixed",
    claimed="g.e_i = e_i for all i",
)
v.record(
    "OP-B-Mass remains explicitly open",
    "still open" in TEX and "single remaining obstacle" in TEX,
    computed="open-status language present",
    claimed="OP-B-Mass not closed",
)
v.record(
    "Conjecture B structural status remains open",
    "Conjecture~B structural & Open" in TEX or "Conjecture~B structural & Open" in TEX.replace(" ", ""),
    computed="status table marks Conjecture B structural open",
    claimed="Conjecture B still requires OP-B-Mass",
)
v.record(
    "OP-B-T2 follows from Z3 decomposition alone",
    False,
    computed="the proof also uses the imported physical sector-gauge map edge/boundary/bulk -> U(1)/SU(2)/G2",
    claimed="consequence of the Z3 decomposition alone",
    detail="Expected proof-scope fail.",
)
v.record(
    "bijection uniqueness is independent of TOE physical identification",
    False,
    computed="the paper's own F4 remark says the stabilizer assignment is a physical TOE Hopf-fibration identification, not abstract JO algebra alone",
    claimed="not a choice / no physical-identification input",
    detail="Expected proof-scope fail.",
)
v.record(
    "top 2 percent gap is explained by computed QCD running correction",
    False,
    computed="the addendum notes QCD running corrections are not included but does not compute a correction that maps 176.1 GeV to 172.7 GeV",
    claimed="2% gap is consistent with QCD running corrections",
    detail="Expected status fail.",
)

sys.exit(v.summary())
