#!/usr/bin/env python3
"""
verify_P004.py -- Paper 04: Three-layer ontology.

This verifier checks the numerical and proof-status claims in
toe/04_Paper_ThreeLayerOntology.tex. The core three-term alpha sum and the
transition-scale formulas are reproducible, but the paper inherits the stale
4*pi^3 value from the early papers. That propagates into the layer budget,
two-layer error table, and several self-lensing comparisons. The audit also
flags proof-status issues: algebraic independence is overstated, the
transition dominance directions are reversed, standard Hopf-fibration facts
are misstated, and the black-hole fold-map claims are not calculable from the
definitions given in the paper.
"""

from __future__ import annotations

import math
import re
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("P004 -- Three-Layer Ontology")

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

PI = math.pi
Q = 4 * PI**3
C = PI**2
M = PI
MU0 = Q + C + M
ALPHA_EXP_INV = 137.035999084
ALPHA = 1 / MU0


def layer_integral(selected: str) -> float:
    total = 0.0
    if "Q" in selected:
        total += Q
    if "C" in selected:
        total += C
    if "M" in selected:
        total += M
    return total


def layer_energy(selected: str) -> float:
    # rho = sum a_n x^n, E = 1/2 int_0^1 (rho')^2 dx.
    layers = {
        "Q": (3, 16 * PI**3),
        "C": (2, 3 * PI**2),
        "M": (1, 2 * PI),
    }
    deriv = [(n - 1, n * a) for key, (n, a) in layers.items() if key in selected]
    total = 0.0
    for power_a, coeff_a in deriv:
        for power_b, coeff_b in deriv:
            total += coeff_a * coeff_b / (power_a + power_b + 1)
    return 0.5 * total


def e_self(selected: str) -> float:
    m0 = layer_integral(selected)
    return layer_energy(selected) / m0**2


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


v.check("alpha inverse from 4*pi^3 + pi^2 + pi", MU0, 137.036303776, rel=1e-12)
v.check(
    "geometric alpha inverse residual percent vs CODATA",
    abs(rel_pct(MU0, ALPHA_EXP_INV)),
    0.000222,
    rel=2e-3,
)
v.check(
    "quantum layer integral 4*pi^3",
    Q,
    123.370055,
    rel=1e-6,
    detail="Expected fail: 4*pi^3 is about 124.025107; 123.370055 is stale.",
)
v.check(
    "listed component sum 123.370055 + 9.869604 + 3.141593",
    123.370055 + 9.869604 + 3.141593,
    137.036303,
    rel=1e-6,
    detail="Expected fail: the listed components sum to about 136.381252.",
)
v.check("classical layer integral pi^2", C, 9.869604, rel=5e-8)
v.check("monadic layer integral pi", M, 3.141593, rel=2e-7)

v.check(
    "f_Q theorem value 0.90006",
    Q / MU0,
    0.90006,
    rel=2e-5,
    detail="Expected fail: with the stated formula the quantum fraction is about 0.90505.",
)
v.check("f_Q later 90.5 percent table", 100 * Q / MU0, 90.5, rel=6e-5)
v.check("f_C = pi^2/mu0", C / MU0, 0.07202, rel=3e-4)
v.check("f_M = pi/mu0", M / MU0, 0.02292, rel=3e-4)

v.record(
    "integrated contributions are algebraically independent over Q",
    False,
    computed="I_C - I_M^2 = pi^2 - pi^2 = 0 and I_Q - 4 I_M^3 = 0",
    claimed="algebraically independent",
    detail="Expected proof-audit fail: the proof establishes Q-linear independence only, not algebraic independence.",
)

qc = layer_integral("QC")
qm = layer_integral("QM")
cm = layer_integral("CM")
v.check(
    "two-layer QC alpha inverse",
    qc,
    133.240,
    rel=1e-5,
    detail="Expected fail: the stated formula gives about 133.895.",
)
v.check(
    "two-layer QC relative error percent",
    abs(rel_pct(qc, MU0)),
    2.77,
    rel=5e-3,
    detail="Expected fail: exact error is about 2.29%, not 2.77%.",
)
v.check(
    "two-layer QM alpha inverse",
    qm,
    126.512,
    rel=1e-5,
    detail="Expected fail: the stated formula gives about 127.167.",
)
v.check(
    "two-layer QM relative error percent",
    abs(rel_pct(qm, MU0)),
    7.68,
    rel=5e-3,
    detail="Expected fail: exact error is about 7.20%, not 7.68%.",
)
v.check("two-layer CM alpha inverse", cm, 13.012, rel=8e-5)
v.check("two-layer CM relative error percent", abs(rel_pct(cm, MU0)), 90.5, rel=6e-5)

x_qc = 3 / (16 * PI)
x_cm = 2 / (3 * PI)
v.check("x_QC transition scale", x_qc, 0.059683, rel=2e-6)
v.check("x_CM transition scale", x_cm, 0.212207, rel=2e-6)
v.check("x_CM/x_QC", x_cm / x_qc, 32 / 9, rel=1e-12)
v.record(
    "QC dominance direction below x_QC",
    (16 * PI**3 * (x_qc / 2) ** 3) > (3 * PI**2 * (x_qc / 2) ** 2),
    computed="at x=x_QC/2, rho_Q < rho_C",
    claimed="for x < x_QC, quantum term dominates",
    detail="Expected fail: the inequality direction is reversed.",
)
v.record(
    "CM dominance direction below x_CM",
    (3 * PI**2 * (x_cm / 2) ** 2) > (2 * PI * (x_cm / 2)),
    computed="at x=x_CM/2, rho_C < rho_M",
    claimed="for x < x_CM, classical term dominates",
    detail="Expected fail: the inequality direction is reversed.",
)
v.record(
    "derivative cascade literally maps quantum term to classical term",
    False,
    computed="d(16*pi^3*x^3)/dx = 48*pi^3*x^2 = 16*pi * rho_C(x)",
    claimed="rho_Q -> quadratic -> rho_C -> linear -> rho_M",
    detail="Expected proof-audit fail: only polynomial degrees line up; the displayed cascade is not an equality chain.",
)

full_energy = layer_energy("QCM")
full_self = e_self("QCM")
v.check("full Dirichlet energy", full_energy, 247485, rel=2e-4)
v.check("full E_self", full_self, 13.177, rel=3e-5)
v.check("Delta E = E_self - 4*pi", full_self - 4 * PI, 0.611, rel=2e-3)

qc_self = e_self("QC")
qm_self = e_self("QM")
cm_self = e_self("CM")
v.check(
    "QC two-layer E_self",
    qc_self,
    13.85,
    rel=5e-4,
    detail="Expected fail: exact two-layer calculation gives about 13.617.",
)
v.check(
    "QM two-layer E_self",
    qm_self,
    15.12,
    rel=5e-4,
    detail="Expected fail: exact two-layer calculation gives about 13.891.",
)
v.check(
    "CM two-layer energy",
    layer_energy("CM"),
    158,
    rel=5e-3,
    detail="Expected fail: exact 1/2 integral is about 790.23.",
)
v.check(
    "CM two-layer E_self",
    cm_self,
    0.93,
    rel=5e-3,
    detail="Expected fail: exact two-layer calculation gives about 4.668.",
)
arena_low = 4 * PI
arena_high = full_self + (full_self - 4 * PI)
v.record(
    "all two-layer self-lensing values fall outside later arena [4*pi, E_self + Delta E]",
    not (arena_low <= qc_self <= arena_high),
    computed=f"QC E_self={qc_self:.6f}, arena=[{arena_low:.6f}, {arena_high:.6f}]",
    claimed="all two-layer values outside oscillation arena",
    detail="Expected fail: the QC two-layer value lies inside the later arena definition.",
)

kappa = ALPHA ** (5 / 4)
v.check("kappa = alpha^(5/4)", kappa, 0.0022, rel=3.2e-2)
v.check("DeltaE/E_self in units of kappa", (full_self - 4 * PI) / full_self / kappa, 22, rel=1.5e-2)
v.check("oscillation amplitude kappa*E_self", kappa * full_self, 0.029, rel=4e-2)
v.check("arena safety factor DeltaE/(kappa E_self)", (full_self - 4 * PI) / (kappa * full_self), 21, rel=4e-2)

mu1 = 16 * PI**3 / 5 + 3 * PI**2 / 4 + 2 * PI / 3
v.check("mu1 first moment", mu1, 108.7167, rel=3e-7)
v.check("mu1/mu0", mu1 / MU0, 0.7933, rel=6e-5)

labels = re.findall(r"\\label\{([^}]+)\}", TEX)
dupes = sorted({label for label in labels if labels.count(label) > 1})
v.record(
    "LaTeX labels are unique",
    not dupes,
    computed=", ".join(dupes) if dupes else "no duplicates",
    claimed="unique theorem/definition labels",
    detail="Expected TeX-audit fail: duplicate labels make cross-references ambiguous.",
)
v.record(
    "Hopf fibration uses S3 as the base of S1 fibers",
    False,
    computed="standard Hopf fibration is S^1 -> S^3 -> S^2; S^3 is total space, S^2 is base",
    claimed="S1 circles as fibers over S3",
    detail="Expected proof-audit fail: later statements sometimes use the correct S2 base, but this proof step is misstated.",
)
v.record(
    "no direct continuous operator B4 -> S1 exists",
    False,
    computed="constant maps B^4 -> S^1 exist, and many smooth maps exist",
    claimed="No direct operator B4 -> S1 exists",
    detail="Expected proof-audit fail: the claimed obstruction is not a topological theorem.",
)
v.record(
    "black-hole fold-map determinant is computable from the definitions in this paper",
    False,
    computed="Pi_up, Pi_down, kernels, and R_Theta are not specified enough to compute DF_Theta or det(DF_Theta)",
    claimed="event horizon/interior/singularity theorem",
    detail="Expected proof-audit fail: this is a geometric sketch/conjecture, not a derived theorem from the given data.",
)

v.check(
    "signed fractional alpha shift from monadic-state change",
    -M / MU0,
    0.023,
    rel=3e-3,
    detail="Expected fail if read as signed: delta alpha / alpha = -delta(alpha^-1)/alpha^-1; the magnitude is about 0.023.",
)
v.check("one-percent state-change magnitude", (M / MU0) * 0.01, 2e-4, rel=1.5e-1)

sys.exit(v.summary())
