#!/usr/bin/env python3
"""
verify_P011.py -- Paper 11: geometric first-principles synthesis.

This verifier checks the main numerical claims in
toe/11_Paper_GeometricFirstPrinciples.tex. The density, equilibrium, and
spectral formula arithmetic is mostly reproducible. The flagged items are
status/proof issues in the synthesis layer: the three formulations are not
mathematically equivalent as written, the "highest precision" / "slightly
lower precision" wording is internally inconsistent, several physical
prediction claims lack the data needed to verify them in this paper, and
"zero free parameters" is stronger than the paper's own open-question caveats.
"""

from __future__ import annotations

import math
import sys
from pathlib import Path



PASS = FAIL = 0
_N = 0

def record(label, ok, computed="", claimed="", detail=""):
    """Modern-format check line; behavior-preserving port of verify_common."""
    global PASS, FAIL, _N
    _N += 1
    ok = bool(ok)
    desc = label
    if ok:
        PASS += 1
    else:
        FAIL += 1
        if "Expected" in detail:
            i = detail.find("Expected")
            desc = f"{label} -- {detail[i:]}"
            detail = detail[:i].rstrip().rstrip(";")
    print(f"  [{'PASS' if ok else 'FAIL'}] {_N:>2}. {desc}")
    if computed != "" or claimed != "":
        print(f"        computed: {computed}")
        print(f"        claimed : {claimed}")
    if detail:
        print(f"        {detail}")
    return ok

def check(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}%"
    return record(label, ok, computed, claimed, err_detail + (f"; {detail}" if detail else ""))

print("P011 -- Geometric First Principles")

ROOT = Path(__file__).resolve().parents[2]
TEX = (ROOT / "toe" / "11_Paper_GeometricFirstPrinciples.tex").read_text()

PI = math.pi
ALPHA_EXP_INV = 137.035999084
M_PL_MEV = 1.2209e22
M_E_MEV = 0.51099895

MU0 = 4 * PI**3 + PI**2 + PI
ALPHA = 1 / MU0
MU1 = 16 * PI**3 / 5 + 3 * PI**2 / 4 + 2 * PI / 3
MU2 = 16 * PI**3 / 6 + 3 * PI**2 / 5 + 2 * PI / 4
MU3 = 16 * PI**3 / 7 + 3 * PI**2 / 6 + 2 * PI / 5
BETA_GEOM = MU1 / MU0

equilibrium_base = 5**4 * (1 / PI - 1 / 10)
equilibrium_correction = 1 + (3 / 4) * MU1 * ALPHA**2
equilibrium_value = equilibrium_base * equilibrium_correction
spectral_log = (3 * PI / 20) * MU1 / (1 - MU1 * ALPHA**2)
actual_log = math.log(M_PL_MEV / M_E_MEV)
beta_qed_geom = 2 * ALPHA**2 / (3 * PI)
beta_ratio = BETA_GEOM / beta_qed_geom
c_const = 10 * MU0**3 / (MU0**2 + MU1)


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


check("4*pi^3", 4 * PI**3, 124.025, rel=1e-6)
check("pi^2", PI**2, 9.870, rel=5e-5)
check("pi", PI, 3.142, rel=2e-4)
check("density alpha inverse", MU0, 137.036303776, rel=1e-12)
check("density residual percent", abs(pct(MU0, ALPHA_EXP_INV)), 0.0002, rel=2e-1)
check("mu1", MU1, 108.716683780, rel=2e-12)
check("mu2", MU2, 90.175963448, rel=3e-12)
check("mu3", MU3, 77.062928817, rel=3e-12)
check("beta_geom = mu1/mu0", BETA_GEOM, 0.793342208, rel=5e-10)

check("equilibrium base", equilibrium_base, 136.443679, rel=2e-9)
check("equilibrium correction", equilibrium_correction, 1.004342, rel=5e-7)
check("equilibrium alpha inverse", equilibrium_value, ALPHA_EXP_INV, rel=1e-6)
check("equilibrium residual percent", abs(pct(equilibrium_value, ALPHA_EXP_INV)), 0.000084, rel=2e-2)
record(
    "equilibrium precision is lower than density precision",
    abs(pct(equilibrium_value, ALPHA_EXP_INV)) > abs(pct(MU0, ALPHA_EXP_INV)),
    f"density residual={abs(pct(MU0, ALPHA_EXP_INV)):.6g}%, equilibrium={abs(pct(equilibrium_value, ALPHA_EXP_INV)):.6g}%",
    "equilibrium slightly lower precision",
    "Expected wording fail: the equilibrium residual is smaller than the density residual.",
)
record(
    "density formulation has highest precision among the three listed formulas",
    abs(pct(MU0, ALPHA_EXP_INV)) < abs(pct(equilibrium_value, ALPHA_EXP_INV)),
    f"density residual={abs(pct(MU0, ALPHA_EXP_INV)):.6g}%, equilibrium={abs(pct(equilibrium_value, ALPHA_EXP_INV)):.6g}%",
    "density highest precision",
    "Expected wording fail: the equilibrium formula is numerically closer to CODATA in this paper.",
)

check("spectral Planck/electron log formula", spectral_log, 51.528, rel=5e-5)
check("actual Planck/electron log", actual_log, 51.528, rel=5e-5)
check("spectral log residual percent", abs(pct(spectral_log, actual_log)), 0.004, rel=4e-2)
check("beta_QED using geometric alpha", beta_qed_geom, 1.130e-5, rel=3e-5)
check("beta_geom / beta_QED", beta_ratio, 70205, rel=2e-5)
check("C constant", c_const, 1362.48, rel=5e-6)
check("beta ratio / actual mass log", beta_ratio / actual_log, 1362.48, rel=5e-5)

check("kappa = alpha^(5/4)", ALPHA ** (5 / 4), 0.00213, rel=2e-3)
check("boundary-modified full correction", 1 / (1 - (3 / 4) * MU1 * ALPHA**2), 1.00436, rel=3e-6)
check("first-order boundary correction", equilibrium_correction, 1.00434, rel=3e-6)
alpha4_term = (3 / 4) ** 2 * (MU1 * ALPHA**2) ** 2
check("alpha^4 correction term estimate", alpha4_term, 1.9e-5, rel=8e-3)
record(
    "alpha^4 correction is beyond current alpha experimental precision",
    alpha4_term < 1e-10,
    f"relative term≈{alpha4_term:.3e}",
    "below current alpha precision",
    "Expected wording fail: 1.9e-5 is far above modern alpha relative experimental precision.",
)

check("T_geom from water triple point", 273.16 / (10 * PI), 8.695, rel=6e-6)
check("water molecular diameter implied by rcrit=3pi*d", 2.59 / (3 * PI), 0.275, rel=1e-3)

record(
    "three formulations are mathematically equivalent as written",
    False,
    "density gives alpha directly, equilibrium uses an optimized correction, and spectral gives a Planck/electron log",
    "mathematically equivalent formulations",
    "Expected synthesis-status fail: they are compatible perspectives, not proved equivalent maps.",
)
record(
    "zero-free-parameter claim is consistent with open mysteries",
    "What is the geometric/algebraic/topological meaning of $5^4 = 625$?" not in TEX,
    "paper says zero free parameters but later lists rho-origin, 5^4, 11pi, and (1/pi-1/10) as open",
    "all numerical values emerge from geometry",
    "Expected status fail: the core numeric formulas are fixed, but not all ingredients are derived from axioms here.",
)
record(
    "S3/Z3 topology proves exactly three fermion families",
    False,
    "the paper states the correspondence but does not derive a theorem that excludes all fourth-family possibilities",
    "fourth generation topologically forbidden",
    "Expected proof-audit fail: this is a structural interpretation, not a proof from the displayed quotient.",
)
record(
    "LEP light-neutrino count confirms no fourth fermion family",
    False,
    "N_nu counts light active neutrino species; it does not by itself exclude a heavy fourth generation",
    "confirmed no fourth generation",
    "Expected status fail: the experimental statement is overbroad.",
)
record(
    "charged-lepton mass prediction is code-verifiable from data in P11",
    False,
    "P11 does not specify lambda_2/lambda_1 or lambda_3/lambda_1 values",
    "verifiable eigenvalue ratios",
    "Expected verifier gap: the claimed 105.7 MeV and 1777 MeV cannot be reproduced from this TeX alone.",
)
record(
    "water nucleation 0.07 percent agreement is derived in P11",
    "classical nucleation theory prediction to 0.07\\%" not in TEX,
    "P11 quotes the agreement but does not compute the classical nucleation-theory comparator",
    "derived 0.07 percent comparison",
    "Expected verifier gap: external inputs are needed.",
)

print(f"\n{'='*60}\nRESULT: {PASS} PASS / {FAIL} FAIL")
sys.exit(0 if FAIL == 0 else 1)
