#!/usr/bin/env python3
"""
verify_P018.py -- Paper 18: master operator assembly.

This verifier checks the explicit constants and internal consistency of the
master-operator construction in toe/18_Paper_MasterOperator.tex. It focuses on
concrete formula claims: rho moments, coefficient values, self-lensing scale,
the first-excited Planck formula, the stated free-ball spectrum, and the
paper's own caveats about assembly uniqueness and mass-spectrum failure.

The coefficient arithmetic mostly reproduces. The main flagged issue is an
internal mismatch: the moment operator is defined with mu_n/mu0, but the
Planck-log formula needs mu1 itself to get 51.53. With the defined normalized
moment expectation, the formula gives about 0.374, not the Planck logarithm.
The paper also acknowledges factor-66 mass failure and open assembly uniqueness,
which contradicts the stronger "complete/no free parameters/spectrum determines
particle masses" wording in the abstract and conclusion.
"""

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 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("P018 -- Master Operator")

ROOT = Path(__file__).resolve().parents[2]
TEX = (ROOT / "toe" / "18_Paper_MasterOperator.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
ALPHA = 1.0 / MU0
KAPPA = ALPHA**1.25
E_SELF = 13.176712697
BETA = 3.0 * PI / 20.0
GAMMA = 3.0 / 4.0
M_NORM_1 = MU1 / MU0
PLANCK_WITH_NORMALIZED_M = BETA * M_NORM_1 / (1.0 - M_NORM_1 * ALPHA**2)
PLANCK_WITH_MU1 = BETA * MU1 / (1.0 - MU1 * ALPHA**2)


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


v.check("mu0 alpha inverse", MU0, 137.036, rel=3e-6)
v.check("mu1", MU1, 108.7167, rel=2e-7)
v.check("alpha coefficient", ALPHA, 1.0 / 137.036, rel=3e-6)
v.check("gamma coefficient", GAMMA, 0.75, rel=1e-12)
v.check("zeta kappa coefficient", KAPPA, 0.002132826, rel=7e-8)
v.check("beta gravity coefficient", BETA, 0.471239, rel=3e-7)
v.check("density coupling integral alpha*mu0", ALPHA * MU0, 1.0, rel=1e-12)
v.check("self-lensing boundary amplitude E_self/m0^2", E_SELF / MU0**2, 0.0007016, rel=5e-4)
v.check("Z3 generator cube roots count", 3, 3, rel=0)
v.record(
    "assembly uniqueness is explicitly open",
    "Whether this is the \\emph{only} admissible assembly is open" in TEX,
    computed="open uniqueness caveat present",
    claimed="assembly uniqueness not proved",
)

v.check("P17 Planck formula using mu1", PLANCK_WITH_MU1, 51.53, rel=4e-5)
v.check(
    "first-excited Planck formula using P18 moment operator definition",
    PLANCK_WITH_NORMALIZED_M,
    51.53,
    rel=1e-3,
    detail="Expected fail: M is defined with mu_n/mu0, so the first-mode expectation gives mu1/mu0 and the formula is about 0.374, not 51.53.",
)
v.record(
    "moment-operator normalization is consistent with gravity theorem",
    False,
    computed="M first-mode eigenvalue = mu1/mu0, but the gravity formula needs mu1",
    claimed="<psi1|M|psi1> feeds the Planck-log formula",
    detail="Expected internal-consistency fail.",
)

v.record(
    "free B4 Dirac/Laplacian spectrum is fixed as (2n+l+2)^2",
    False,
    computed="on a ball, Laplacian/Dirac spectra depend on boundary conditions and Bessel/Dirac radial zeros; the displayed formula is not the generic B4 ball spectrum",
    claimed="E_nl=(2n+l+2)^2 for D_B4^2 alone",
    detail="Expected spectral-formula fail.",
)
v.record(
    "ground-state alpha normalization follows from the master eigenproblem",
    False,
    computed="the paper states int |psi0|^2 rho dr = alpha^-1 but does not solve for psi0 or normalize it; alpha^-1 follows only for a constant unit profile",
    claimed="ground state normalization yields alpha^-1",
    detail="Expected proof-status fail.",
)

v.check("mass formula failure factor", 206.8 / 3.1, 66.0, rel=2e-2)
v.record(
    "canonical spectrum quantitatively determines fermion masses",
    False,
    computed="the paper's own mass-gap remark says m_mu/m_e≈3.1 versus 206.8 and no quantitative lepton ratios are computed",
    claimed="discrete spectrum encodes particle masses",
    detail="Expected status fail.",
)
v.record(
    "no-free-parameters conclusion is consistent with caveats",
    False,
    computed="assembly uniqueness is open, mass ratios fail by factor ~66, and several spectral reductions are asserted rather than derived",
    claimed="No free parameters remain / complete operator-theoretic foundation",
    detail="Expected status fail.",
)
v.record(
    "Schrodinger/Yang-Mills/Einstein/Dirac reductions are derived in P18",
    False,
    computed="the limits are stated schematically; no derivation of SM Yang-Mills equations, Einstein equations, anomaly cancellation, or particle masses from the operator is supplied",
    claimed="UFE reduces to the main physical field equations",
    detail="Expected proof-status fail.",
)

sys.exit(v.summary())
