#!/usr/bin/env python3
"""
verify_P126.py -- Addendum 126: T_F = 1/2 from Peirce/Jordan normalization.

This verifier confirms the trace-scaling arithmetic and flags the algebraic
identification gaps around SU(3), Im(O), and the Jordan-generator prescription.
"""

from __future__ import annotations

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("P126 -- Fundamental Trace Normalization")

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


v.record("TeX source is present", "T_F = 1/2" in TEX and "Jordan Triple Product" in TEX)

# Standard SU(3) and Albert-algebra dimension arithmetic.
v.check("SU(3) generator count", 3**2 - 1, 8, rel=0)
v.check("Peirce off-diagonal dimension over O", 8, 8, rel=0)
v.check("J3(O) real dimension", 3 + 3 * 8, 27, rel=0)
v.check("C_A for SU(3)", 3, 3, rel=0)
v.check("C_F standard SU(3) formula", (3**2 - 1) / (2 * 3), 4 / 3, rel=1e-15)

# Trace normalization arithmetic conditional on an orthonormal 8-dimensional O-basis.
raw_trace_same = 2.0
raw_trace_orthogonal = 0.0
tf_same = (0.5**2) * raw_trace_same
tf_orthogonal = (0.5**2) * raw_trace_orthogonal
v.check("raw Peirce trace for same orthonormal generator", raw_trace_same, 2.0, rel=0)
v.check("raw Peirce trace for orthogonal generators", raw_trace_orthogonal, 0.0, abs_tol=0.0)
v.check("Jordan-scaled trace for same generator", tf_same, 0.5, rel=0)
v.check("Jordan-scaled trace for orthogonal generators", tf_orthogonal, 0.0, abs_tol=0.0)
v.check("T_F residual", tf_same - 0.5, 0.0, abs_tol=0.0)

# QCD beta-function arithmetic for n_f=5, using the displayed Casimir triple.
ca = 3.0
cf = 4.0 / 3.0
tf = 0.5
nf = 5.0
b1 = (34.0 / 3.0) * ca * ca - (20.0 / 3.0) * ca * tf * nf - 4.0 * cf * tf * nf
v.check("two-loop b1 from displayed Casimirs for nf=5", b1, 116.0 / 3.0, rel=1e-15)

v.record(
    "eight orthonormal unit imaginary octonions exist",
    False,
    computed="Im(O) has real dimension 7, so it cannot contain an 8-element orthonormal basis",
    claimed="{e_a}_{a=1}^8 is an orthonormal basis of Im(O)",
    detail="Expected fail: this is the central dimension mismatch.",
)
v.record(
    "SU(3) adjoint generators embed as a subspace of Im(O)",
    False,
    computed="su(3) has dimension 8 and sits in g2 as derivations stabilizing a unit imaginary octonion; it is not an 8-dimensional subspace of the 7-dimensional Im(O)",
    claimed="the SU(3) octet maps to the imaginary octonions as the relevant subspace",
    detail="Expected representation-identification fail.",
)
v.record(
    "Hurwitz norm identity forces generator orthonormality",
    False,
    computed="N(xy)=N(x)N(y) is multiplicativity of the norm; it does not force a chosen generator set to be orthonormal",
    claimed="orthonormality is forced by the Hurwitz norm identity",
    detail="Expected assumption/proof fail.",
)
v.record(
    "T^a = X_a/2 is derived rather than a normalization choice",
    False,
    computed="the Jordan product has a 1/2 in L_X(Y)=X o Y, but identifying the matrix representative of a Lie generator with X_a/2 is an additional representation prescription",
    claimed="Definition of Jordan generator is not a choice",
    detail="Expected derivation-status fail.",
)
v.record(
    "derivation avoids the standard Gell-Mann normalization",
    False,
    computed="the calculation first obtains Tr(X_a X_b)=2 delta_ab and then sets T^a=X_a/2, exactly mirroring lambda^a -> lambda^a/2 at the level of trace scaling",
    claimed="without reference to the standard generator normalisation convention",
    detail="Expected independence/novelty fail.",
)
v.record(
    "global associative matrix product is available in J3(O)",
    False,
    computed="octonionic matrix multiplication is not associative in general; the displayed two-factor Peirce product is well-defined, but the wording 'associative matrix product' is too broad",
    claimed="compute the associative matrix product X_a X_b in J3(O)",
    detail="Expected algebra-scope fail.",
)
v.record(
    "b1 is fully first-principles closed by this addendum",
    False,
    computed="C_F is still taken from the standard SU(N) formula and the T_F derivation depends on the unproved SU(3)-to-Peirce generator identification",
    claimed="the two-loop coefficient b1=116/3 is fully derived from first principles",
    detail="Expected closure-status fail.",
)
v.record(
    "adjoint trace convention is unambiguous",
    False,
    computed="the text states T_A=C_A=3, then also references an alternative convention T_A=C_A/2=3/2",
    claimed="T_A = C_A/2 = 3/2 for the adjoint representation",
    detail="Expected convention ambiguity.",
)
v.record(
    "T_F=1/2 for all SU(N) follows from the displayed J3(O) argument",
    False,
    computed="the proof is specific to a Peirce embedding with unit-norm generators; no Jordan embedding for arbitrary SU(N) is constructed",
    claimed="universality across all SU(N) is thus a theorem of Jordan algebra structure",
    detail="Expected generalization fail.",
)

sys.exit(v.summary())
