#!/usr/bin/env python3
"""
verify_P005.py -- Paper 5: narrative geometry of reality.

This verifier checks the narrative paper's reused alpha, layer, energy,
oscillation, and beta-function arithmetic, and flags the stale/proof-status
claims that propagate from earlier papers.
"""

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 adapter: identical tolerance logic, modern output format."""

    def __init__(self, name: str):
        self.name = name
        self.results = []
        print(name)

    def record(self, label, ok, computed="", claimed="", detail=""):
        self.results.append(CheckResult(label, ok, computed, claimed, detail))
        n = len(self.results)
        desc, info = label, detail
        i = detail.find("Expected")
        if i >= 0:
            desc = f"{label} -- {detail[i:]}"
            info = 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 info:
            print(f"        {info}")
        return bool(ok)

    def summary(self) -> int:
        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("P005 -- Geometry of Reality")

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

PI = math.pi
MU0 = 4.0 * PI**3 + PI**2 + PI
ALPHA = 1.0 / MU0
KAPPA = ALPHA**1.25
MU1 = 16.0 * PI**3 / 5.0 + 3.0 * PI**2 / 4.0 + 2.0 * PI / 3.0
BETA_GEOM = MU1 / MU0
BETA_QED = 2.0 / (3.0 * PI * MU0**2)
BETA_RATIO = BETA_GEOM / BETA_QED
C_COEFF = 10.0 * MU0**3 / (MU0**2 + MU1)

ENERGY = 0.5 * (
    (48.0 * PI**3) ** 2 / 5.0
    + (6.0 * PI**2) ** 2 / 3.0
    + (2.0 * PI) ** 2
    + 2.0 * (48.0 * PI**3) * (6.0 * PI**2) / 4.0
    + 2.0 * (48.0 * PI**3) * (2.0 * PI) / 3.0
    + 2.0 * (6.0 * PI**2) * (2.0 * PI) / 2.0
)
E_SELF = ENERGY / MU0**2
DELTA_E = E_SELF - 4.0 * PI


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


v.check("alpha inverse formula", MU0, 137.036303776, rel=1e-11)
v.check("CODATA relative alpha error percent", abs(rel_percent(MU0, 137.035999084)), 0.000222, rel=3e-3)
v.check("boundary pi^2 contribution", PI**2, 9.8696, rel=5e-6)
v.check("edge pi contribution", PI, 3.1416, rel=3e-6)
v.check("bulk fraction percent", 100.0 * (4.0 * PI**3) / MU0, 90.5, rel=6e-4)
v.check("boundary fraction percent", 100.0 * PI**2 / MU0, 7.2, rel=4e-3)
v.check("edge fraction percent", 100.0 * PI / MU0, 2.3, rel=5e-3)
v.check("E functional", ENERGY, 247_445.0, rel=8e-7)
v.check("E_self normalized", E_SELF, 13.177, rel=3e-5)
v.check("floor 4pi", 4.0 * PI, 12.566, rel=4e-5)
v.check("Delta E", DELTA_E, 0.611, rel=2e-3)
v.check("Delta E / E_self", DELTA_E / E_SELF, 0.0463, rel=5e-4)
v.check("kappa alpha^(5/4)", KAPPA, 0.00213, rel=2e-3)
v.check("kappa observed-vs-predicted residual", abs(0.00220 - KAPPA) / 0.00220, 0.03, rel=8e-2)
v.check("kappa E_self amplitude", KAPPA * E_SELF, 0.029, rel=4e-2)
v.check("omega1", PI * math.sqrt(1.0 - KAPPA), 3.138, rel=1e-4)
v.check("log-energy period", 2.0 * PI / (PI * math.sqrt(1.0 - KAPPA)), 2.0, rel=2e-3)
v.check("beta_geom", BETA_GEOM, 0.793342, rel=3e-7)
v.check("beta_QED", BETA_QED, 1.130e-5, rel=3e-5)
v.check("beta ratio", BETA_RATIO, 70_205.48, rel=5e-6)
v.check("C coefficient", C_COEFF, 1362.48, rel=4e-6)
v.check("ratio/C Planck-log scale", BETA_RATIO / C_COEFF, 51.528, rel=3e-6)

v.check(
    "bulk contribution 4*pi^3",
    4.0 * PI**3,
    123.370055012,
    rel=1e-6,
    detail="Expected fail: 4*pi^3 is about 124.0251067; 123.370055 is stale.",
)
v.check(
    "displayed relative-error formula uses correct CODATA denominator",
    abs((137.036304 - 137.036999) / 137.036999),
    2.2e-6,
    rel=1e-2,
    detail="Expected fail: the displayed formula uses 137.036999, not CODATA 137.035999, and evaluates near 5.1e-6.",
)
v.check(
    "quantum + classical two-layer value",
    4.0 * PI**3 + PI**2,
    133.24,
    rel=1e-4,
    detail="Expected fail: exact value is about 133.895; 133.24 follows from the stale 4*pi^3 number.",
)
v.check(
    "quantum + observational two-layer value",
    4.0 * PI**3 + PI,
    126.51,
    rel=1e-4,
    detail="Expected fail: exact value is about 127.167; 126.51 follows from the stale 4*pi^3 number.",
)
v.check(
    "QC two-layer error percent",
    abs(rel_percent(4.0 * PI**3 + PI**2, MU0)),
    2.8,
    rel=2e-2,
    detail="Expected fail: exact omission of the edge term is 2.2925%, not 2.8%.",
)
v.check(
    "QO two-layer error percent",
    abs(rel_percent(4.0 * PI**3 + PI, MU0)),
    7.7,
    rel=2e-2,
    detail="Expected fail: exact omission of the boundary term is 7.202%, not 7.7%.",
)
v.check(
    "coefficient variant {15,3,2}",
    15.0 * PI**3 / 4.0 + 3.0 * PI**2 / 3.0 + 2.0 * PI / 2.0,
    133.3,
    rel=1e-3,
    detail="Expected fail: under the density-coefficient convention it gives about 129.285, not 133.3.",
)
v.check(
    "omega1 printed value 3.136",
    PI * math.sqrt(1.0 - KAPPA),
    3.136,
    rel=1e-4,
    detail="Expected fail: exact kappa gives omega1 about 3.13824.",
)
v.check(
    "mass-ratio toy example",
    0.830 ** -19,
    82.0,
    rel=2e-2,
    detail="Expected fail: 0.830^-19 is about 34.48; the claimed 82 is stale.",
)
v.check(
    "toy mu/e discrepancy factor",
    206.768 / (0.830 ** -19),
    2.5,
    rel=5e-2,
    detail="Expected fail: with the stated formula the discrepancy is about 6x, not 2.5x.",
)
v.record(
    "wave equation has rho_cubic as exact equilibrium",
    False,
    computed="substituting rho=rho_cubic cancels only the nonlinear term and leaves rho_cubic'' on the RHS",
    claimed="nonlinear term vanishes identically, confirming exact equilibrium",
    detail="Expected inherited P2/P3 wave-equation fail.",
)
v.record(
    "linearization yields eta_tt=(1-kappa)eta_xx",
    False,
    computed="linearizing the written nonlinear term produces additional eta*rho_cubic'' structure unless more assumptions are added",
    claimed="linearization yields modified wave equation with speed 1-kappa",
    detail="Expected inherited wave-equation fail.",
)
v.record(
    "5/4 is globally selected by exponent scan",
    False,
    computed="the table compares only a few candidate exponents; it does not prove a global uniqueness/minimization theorem",
    claimed="5/4 minimizes error and has clear geometric meaning",
    detail="Expected proof-status fail.",
)
v.record(
    "L(4,1) is incompatible with S3",
    False,
    computed="lens spaces L(p,q), including L(4,1), are quotients of S3 by free cyclic actions; the issue is physical identification, not nonexistence",
    claimed="There is no L(4,1) compatible with S3 geometry",
    detail="Expected topology fail.",
)
v.record(
    "Z3 lens space topologically forbids any fourth family",
    False,
    computed="the quotient gives a threefold cover under the chosen Z3 action, but does not prove that no other representation copy or family mechanism can exist",
    claimed="fourth generation is topologically impossible",
    detail="Expected proof-status fail.",
)
v.record(
    "strong CP problem is resolved in P5",
    False,
    computed="P5 asserts a geometric strong-CP solution in narrative form but supplies no theta_QCD/action/path-integral derivation",
    claimed="framework resolves the strong CP problem geometrically",
    detail="Expected derivation fail.",
)
v.record(
    "random-coefficient probability estimate is reproducible",
    False,
    computed="brute-force count over a,b,c in 1..20 for a*pi^3+b*pi^2+c*pi gives 1 hit in 8000, not the displayed continuum estimate ~1e-6",
    claimed="probability of a random near-hit is ~1e-6",
    detail="Expected statistical-model fail.",
)

sys.exit(v.summary())
