#!/usr/bin/env python3
"""
verify_P001.py -- Paper 01: The Perfect Stable Sphere.

This verifier checks the main numerical claims in
toe/01_Paper_PerfectStableSphere.tex.

The fine-structure integral, octonionic bulk scale, kappa-scale estimates, and
some oscillation arithmetic are reproducible. The audit flags the central
energy theorem, the moment/mass-scaling table, the neutrino suppression
arithmetic, and a CP/Jarlskog formula issue.
"""

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("P001 -- Perfect Stable Sphere")

PI = math.pi
A3 = 16 * PI**3
A2 = 3 * PI**2
A1 = 2 * PI
MU0 = 4 * PI**3 + PI**2 + PI
ALPHA = 1 / MU0
ALPHA_EXP_INV = 137.035999084
KAPPA = 0.0022


def mu(n: int) -> float:
    return A3 / (n + 4) + A2 / (n + 3) + A1 / (n + 2)


energy = 0.5 * (
    (48 * PI**3) ** 2 / 5
    + (6 * PI**2) ** 2 / 3
    + (2 * PI) ** 2
    + 2 * (48 * PI**3) * (6 * PI**2) / 4
    + 2 * (48 * PI**3) * (2 * PI) / 3
    + 2 * (6 * PI**2) * (2 * PI) / 2
)
e_scaled = energy / MU0**2

v.check("4*pi^3 contribution", 4 * PI**3, 123.370055, rel=5e-9,
        detail="Expected fail: documents the paper's historical printed value"
        " 123.370055 for the 4*pi^3 term; the true value is 124.0251.")
v.check("pi^2 contribution", PI**2, 9.869604, rel=5e-8)
v.check("pi contribution", PI, 3.141593, rel=2e-7)
v.check("rho integral alpha inverse", MU0, 137.036303776, rel=1e-12)
v.check("alpha inverse relative precision percent", 100 * (MU0 - ALPHA_EXP_INV) / ALPHA_EXP_INV, 0.0002, rel=2e-1)

bulk_r = (8 * PI) ** (1 / 3)
v.check("bulk scale R=(8*pi)^(1/3)", bulk_r, 2.929, rel=1e-4)
v.check("bulk volume coefficient from R", 2 * PI**2 * bulk_r**3, 16 * PI**3, rel=1e-12)

v.check(
    "Dirichlet energy from displayed integral",
    energy,
    18791.3,
    rel=1e-3,
    detail="Expected fail: the displayed integral evaluates to about 247444.81, not 18791.3.",
)
v.check("m0^2", MU0**2, 18778.9, rel=5e-6)
v.check(
    "scaled energy E/m0^2",
    e_scaled,
    1.00066,
    rel=1e-3,
    detail="Expected fail: using the displayed rho gives about 13.1767.",
)
v.check(
    "exact symbolic scaled energy equals 1",
    e_scaled,
    1.0,
    rel=1e-12,
    detail="Expected fail: the exact symbolic value is not 1.",
)
v.record(
    "energy theorem stationary point follows from E[rho]=m0^2",
    False,
    computed=f"E/m0^2={e_scaled:.6f}",
    claimed="E/m0^2=1 to machine precision",
    detail="Expected fail: the premise used to motivate the later wave equation is numerically false.",
)

kappa_alpha = ALPHA ** (5 / 4)
v.check("candidate kappa alpha^(5/4)", kappa_alpha, 0.002133, rel=2e-4)
v.check("kappa-alpha relative error", abs(KAPPA - kappa_alpha) / KAPPA, 0.031, rel=2e-2)
v.check("R for kappa plus branch", 1 / math.sqrt(1 - KAPPA), 1.001, rel=2e-4)
v.check("R for kappa minus branch", 1 / math.sqrt(1 + KAPPA), 0.999, rel=2e-4)

beta_geom = mu(1) / mu(0)
omega1 = PI * math.sqrt(1 - KAPPA)
v.check("fundamental omega_1", omega1, 3.138, rel=2e-4)
v.check("physical omega = omega_1*beta_geom", omega1 * beta_geom, 2.49, rel=2e-3)
v.check("oscillation amplitude percent", 100 * KAPPA, 0.2, rel=1e-1)

v.check("mu0", mu(0), 137.036304, rel=2e-9)
v.check("mu1", mu(1), 108.716684, rel=3e-9)
v.check("mu2", mu(2), 90.175963, rel=5e-9)
v.check(
    "mu3",
    mu(3),
    77.083412,
    rel=1e-6,
    detail="Expected fail: the moment formula gives about 77.062929.",
)
v.check("beta_geom ratio", beta_geom, 0.7933, rel=1e-4)
v.check("mu2/mu1", mu(2) / mu(1), 0.8295, rel=1e-4)
v.check("mu3/mu2", mu(3) / mu(2), 0.8546, rel=1e-4)

mass_prediction = (mu(2) / mu(1)) ** (-19)
v.check(
    "mass scaling with beta=-19",
    mass_prediction,
    82.0,
    rel=1e-2,
    detail="Expected fail: beta=-19 gives about 34.9; 82 would require beta about -23.6.",
)
v.check("42 MeV / 0.511 MeV", 42 / 0.511, 82.0, rel=3e-3)
v.check("experimental mu/e mass ratio", 105.658 / 0.51099895, 207.0, rel=2e-3)
v.check(
    "mass hierarchy discrepancy factor using beta=-19 prediction",
    (105.658 / 0.51099895) / mass_prediction,
    2.5,
    rel=5e-2,
    detail="Expected fail: using the actual beta=-19 prediction gives a factor about 5.9.",
)

suppression = (1 / 70) * (1 / 137) * (PI / 2) * (1 / 137)
v.check(
    "combined neutrino suppression from listed factors",
    1 / suppression,
    2.5e6,
    rel=5e-2,
    detail="Expected fail: the listed factors give about 8.36e5, not 2.5e6.",
)
v.check(
    "1 GeV divided by claimed 2.5e6 suppression in eV",
    1e9 / 2.5e6,
    0.4,
    rel=1e-3,
    detail="Expected fail: 1 GeV / 2.5e6 is 400 eV, not 0.4 eV.",
)
v.check("1/kappa geometric length", 1 / KAPPA, 455, rel=2e-3)
v.check("geometric length in km", (1 / KAPPA) * 220, 100000, rel=2e-3)
v.record(
    "Z3 mass-matrix small-b assumption",
    False,
    computed="Delta m^2 ratio ~30 implies b/a is order 10 under the paper's linear estimate",
    claimed="b << a",
    detail="Expected fail: the stated estimate is incompatible with the small-b expansion.",
)

theta12_tbm = math.degrees(math.asin(1 / math.sqrt(3)))
v.check("TBM theta12", theta12_tbm, 35.26, rel=2e-4)
v.check("TBM theta23", 45.0, 45.0, rel=1e-12)
v.check("TBM theta13", 0.0, 0.0, abs_tol=1e-12)
v.check("theta12 distance from quoted experiment", abs(theta12_tbm - 33.41), 1.85, rel=2e-2)
v.check("theta23 distance from quoted experiment", abs(45.0 - 49.0), 4.0, rel=1e-12)
v.check("theta13 distance from quoted experiment", abs(0.0 - 8.57), 8.57, rel=1e-12)

cp_sigma = abs(240 - 197) / 25
v.check("CP 240 deg distance in quoted sigmas", cp_sigma, 1.72, rel=1e-3)
epsilon = (197 - 240) / 240
v.check("CP epsilon", epsilon, -0.18, rel=5e-2)
v.check("sum of listed CP correction scales", 0.002 + 0.01 + 0.10 + 0.10, 0.21, rel=1e-2)
v.check(
    "240 deg times O(kappa) uncertainty",
    240 * KAPPA,
    10.0,
    rel=1e-2,
    detail="Expected fail: O(kappa) around 240 degrees is about 0.53 degrees, not +/-10 degrees.",
)

s = lambda deg: math.sin(math.radians(deg))
c = lambda deg: math.cos(math.radians(deg))
j_paper = s(240) * s(33.4) * s(49) * s(8.6)
j_standard = j_paper * c(33.4) * c(49) * c(8.6) ** 2
v.check("paper sine-only Jarlskog arithmetic", j_paper, -0.054, rel=5e-3)
v.check(
    "standard PMNS Jarlskog with cosine factors",
    j_standard,
    -0.054,
    rel=1e-2,
    detail="Expected fail: the standard formula gives about -0.0288 for these angles and delta=240 deg.",
)

sys.exit(v.summary())
