#!/usr/bin/env python3
"""
verify_P028.py -- Paper 28: universal wave geometry.

This verifier checks the concrete quaternion/Hopf, volume-ratio, Theta-cycle,
and moment identities in toe/28_Paper_UniversalWaveGeometry.tex. It also
separates those identities from broader physical-status claims: identifying
the Hopf observable with SR velocity, exact arc-speed normalization, simulation
RMSE claims, and the upstream J3(O) embedding.

Most displayed geometry reproduces. Flagged issues are status/reproducibility:
the file header says Paper 27, the SR-lapse theorem is an identity plus a
physical identification rather than a derivation of physical velocity, the
2*pi arc-speed is a normalization/approximate lift rather than exact from the
given kappa formula, and simulation/J3(O) claims are not reproducible from the
TeX alone.
"""

from __future__ import annotations

import math
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("P028 -- Universal Wave Geometry")

ROOT = Path(__file__).resolve().parents[2]
TEX = (ROOT / "toe" / "28_Paper_UniversalWaveGeometry.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
V3 = 4.0 * PI / 3.0
V6 = PI**3 / 6.0
MEASURE_RATIO = V6 / V3
OMEGA0 = 2.0 * PI * MEASURE_RATIO
OMEGA1 = PI * math.sqrt(1.0 - KAPPA)
LIFTED_SPEED = 2.0 * OMEGA1


def theta(x: float) -> float:
    return 4.0 * PI**3 * x**4 + PI**2 * x**3 + PI * x**2


def rho(x: float) -> float:
    return 16.0 * PI**3 * x**3 + 3.0 * PI**2 * x**2 + 2.0 * PI * x


def hopf_v_from_beta(beta: float) -> float:
    a = math.cos(beta) * math.cos(0.37)
    b = math.cos(beta) * math.sin(0.37)
    c = math.sin(beta) * math.cos(1.21)
    d = math.sin(beta) * math.sin(1.21)
    return (a * a + b * b) - (c * c + d * d)


def axis_map(r: float, nx: float) -> float:
    eta = 2.0 * r
    return nx * nx + (1.0 - nx * nx) * math.cos(eta)


v.record(
    "file header paper number matches P28",
    "% Paper 28:" in TEX,
    computed="header starts with '% Paper 27:'" if "% Paper 27:" in TEX else "header not found",
    claimed="Paper 28",
    detail="Expected metadata fail.",
)
v.check("monad integral alpha inverse", MU0, 137.036, rel=3e-6)
v.check("Theta(1)", theta(1.0), MU0, rel=1e-12)
v.check("bulk phase contribution", 4.0 * PI**3, 124.0251, rel=1e-6)
v.check("boundary phase contribution", PI**2, 9.8696, rel=5e-6)
v.check("edge phase contribution", PI, 3.14159, rel=1e-6)
v.check("mu1 downward Jacobian", MU1, 108.7167, rel=2e-7)
v.check("mu1/mu0 ratio", MU1 / MU0, 0.7933, rel=6e-5)
v.record(
    "Theta is increasing and convex on [0,1]",
    rho(0.0) == 0.0 and rho(1.0) > 0.0 and (48.0 * PI**3 * 0.0**2 + 6.0 * PI**2 * 0.0 + 2.0 * PI) > 0.0,
    computed="rho'(x)=48*pi^3*x^2+6*pi^2*x+2*pi is positive for x>=0",
    claimed="Theta strictly increasing and convex",
)

for beta in [0.0, 0.17, 0.4, PI / 4.0, 1.2]:
    v.check(f"Hopf v=cos(2 beta) at beta={beta:.3f}", hopf_v_from_beta(beta), math.cos(2.0 * beta), rel=1e-12, abs_tol=1e-12)
    m = math.sqrt(max(0.0, 1.0 - hopf_v_from_beta(beta) ** 2))
    v.check(f"Hopf complement |sin(2 beta)| at beta={beta:.3f}", m, abs(math.sin(2.0 * beta)), rel=1e-12, abs_tol=1e-12)

test_axes = [(0.2, 0.0), (0.5, 0.3), (1.1, 0.8), (1.4, 1.0)]
for r, nx in test_axes:
    eta = 2.0 * r
    alternate = 1.0 - 2.0 * (1.0 - nx * nx) * math.sin(eta / 2.0) ** 2
    v.check(f"axis-resolved map at r={r:.2f}, n_parallel={nx:.1f}", axis_map(r, nx), alternate, rel=1e-12, abs_tol=1e-12)

v.check("V3 unit ball", V3, 4.0 * PI / 3.0, rel=1e-12)
v.check("V6 unit ball", V6, PI**3 / 6.0, rel=1e-12)
v.check("V6/V3", MEASURE_RATIO, PI**2 / 8.0, rel=1e-12)
v.check("measure ratio decimal", MEASURE_RATIO, 1.23370, rel=5e-6)
v.check("Omega0", OMEGA0, PI**3 / 4.0, rel=1e-12)
v.check("Omega0 decimal", OMEGA0, 7.7516, rel=4e-6)
v.check("kappa", KAPPA, 0.002132826, rel=7e-8)
v.check("fundamental density mode omega1", OMEGA1, PI * math.sqrt(1.0 - KAPPA), rel=1e-12)
v.check(
    "lifted speed equals exactly 2*pi",
    LIFTED_SPEED,
    2.0 * PI,
    rel=1e-5,
    detail="Expected fail: 2*pi*sqrt(1-kappa) is slightly below 2*pi; the text later treats 2*pi as a normalization/approximation.",
)
v.check("lifted-speed fractional residual percent", 100.0 * (LIFTED_SPEED - 2.0 * PI) / (2.0 * PI), -0.1067, rel=2e-3)

v.record(
    "Lorentz lapse is derived as physical SR time dilation",
    False,
    computed="the Hopf identity gives sqrt(1-v^2) once v is defined, but the physical identification of Hopf v with SR velocity is an additional modelling step",
    claimed="proper-time dilation emerges with no insertion of Minkowski structure",
    detail="Expected physical-identification fail.",
)
v.record(
    "simulation RMSE claims are reproducible from the TeX alone",
    False,
    computed="the paper quotes numerical verification/RMSE but provides no simulation data or harness in the TeX",
    claimed="RMSE ~1e-14 and best-fit Omega0 agreement <3e-5",
    detail="Expected reproducibility fail.",
)
v.record(
    "Omega0 is forced by volume ratio without modelling assumptions",
    False,
    computed="V6/V3 is exact, but choosing this volume ratio as the SR lapse normalization is a modelling prescription, not forced by the algebra alone",
    claimed="Omega0 is forced, not fitted",
    detail="Expected derivation-status fail.",
)
v.record(
    "J3(O) upstream embedding is explicitly constructed",
    False,
    computed="the final section sketches a slice/cascade but does not construct the associative subalgebra choice or prove the observer pair descends from J3(O) invariants",
    claimed="J3(O) provides natural upstream embedding",
    detail="Expected proof-status fail.",
)
v.record(
    "Theta scaling by alpha worsens SR agreement is data-backed in TeX",
    False,
    computed="the statement is based on numerical experiments not included in the TeX",
    claimed="multiplying Theta by alpha or alpha^-1 worsens the SR lapse agreement",
    detail="Expected reproducibility fail.",
)

sys.exit(v.summary())
