#!/usr/bin/env python3
"""
verify_P032.py -- Paper 32: dark energy as B4 corner residual.

This verifier checks the corner-residual arithmetic in
32_Paper_DarkEnergyCornerResidual.tex and the dynamic-lambda addendum. The
main Lambda0 numerical value reproduces; the audit flags geometry/counting
issues around 4-cube corners/vertices and proof-status issues in the Euler and
octonion interpretations.
"""

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):
    """Output adapter: modern check-line format. Tolerance logic is
    inherited unchanged from verify_common.Verifier; only printing and
    the footer differ."""

    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)
        expected = (not ok) and ("Expected" in str(detail))
        desc = f"{label} -- {detail}" if expected else label
        print(f"  [{'PASS' if ok else 'FAIL'}] {n:>2}. {desc}")
        if computed != "" or claimed != "":
            print(f"       computed: {computed}")
            print(f"       claimed : {claimed}")
        if detail and not expected:
            print(f"       {detail}")
        return ok

    def summary(self):
        passed = sum(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("P032 -- Dark Energy Corner Residual")

ROOT = Path(__file__).resolve().parents[2]
TEX = (ROOT / "toe" / "32_Paper_DarkEnergyCornerResidual.tex").read_text()
ADDENDUM = (ROOT / "toe" / "32_Addendum_DynamicLambda.tex").read_text()

PI = math.pi
LAMBDA0 = 1.0 - PI**2 / 32.0
PLANCK = 0.6847
SIGMA = 0.0073
ALPHA_INV = 4.0 * PI**3 + PI**2 + PI
EPS = PI / ALPHA_INV


def ball_volume(d: int) -> float:
    return PI ** (d / 2.0) / math.gamma(d / 2.0 + 1.0)


def lambda_dim(d: int) -> float:
    return 1.0 - ball_volume(d) / (2.0**d)


def chi_sphere(n: int) -> int:
    return 1 + (-1) ** n


v.check("V4 unit ball", ball_volume(4), PI**2 / 2.0, rel=1e-12)
v.check("hypercube volume [-1,1]^4", 2.0**4, 16.0, rel=0)
v.check("covered fraction pi^2/32", PI**2 / 32.0, 0.3084, rel=5e-4)
v.check("Lambda0", LAMBDA0, 0.6916, rel=4e-5)
v.check("Planck discrepancy", abs(LAMBDA0 - PLANCK), 0.0069, rel=4e-3)
v.check("Planck sigma offset", abs(LAMBDA0 - PLANCK) / SIGMA, 0.94, rel=3e-3)
v.check("dimensional cascade d=2", lambda_dim(2), 1.0 - PI / 4.0, rel=1e-12)
v.check("dimensional cascade d=3", lambda_dim(3), 1.0 - PI / 6.0, rel=1e-12)
v.check("dimensional cascade d=6", lambda_dim(6), 1.0 - PI**3 / 192.0, rel=1e-12,
        detail="Expected fail: documents the recorded d=6 cascade claim 1 - pi^3/192;"
        " the recursion gives 0.91925, not 0.83851.")
v.check("d=4 closest among d=1..8 to Planck value", min(range(1, 9), key=lambda d: abs(lambda_dim(d) - PLANCK)), 4, rel=0)

v.check("Euler cube-net bounded plus exterior faces", 6 + 1, 7, rel=0)
v.check("octonion basis dimension", 1 + 7, 8, rel=0)
v.check("edge fraction epsilon", EPS, 0.0229, rel=2e-3)
v.check("maximum delta Lambda", 2.0 * EPS * LAMBDA0, 0.032, rel=1e-2)
v.check("fractional H0 shift estimate", EPS * LAMBDA0 / (2.0 * (0.315 + PLANCK)), 0.008, rel=1e-2)
v.check("delta H0 at 67 km/s/Mpc", 67.0 * EPS * LAMBDA0 / (2.0 * (0.315 + PLANCK)), 0.5, rel=7e-2)

C_values = {k: sum(chi_sphere(n) for n in [3, 2, 1, 0][:k]) for k in range(5)}
v.check("dynamic addendum C(0)", C_values[0], 0, rel=0)
v.check("dynamic addendum C(1)", C_values[1], 0, rel=0)
v.check("dynamic addendum C(2)", C_values[2], 2, rel=0)
v.check("dynamic addendum C(3)", C_values[3], 2, rel=0)
v.check("dynamic addendum C(4)", C_values[4], 4, rel=0)
v.check("dynamic Lambda(2)", LAMBDA0 * 4.0 / C_values[2], 1.383, rel=2e-4)
v.check("dynamic Lambda(4)", LAMBDA0 * 4.0 / C_values[4], LAMBDA0, rel=1e-12)
v.record(
    "dynamic addendum records Hubble derivation as open",
    "Hubble tension" in ADDENDUM and "premature" in ADDENDUM,
    computed="Hubble-tension caveat found",
    claimed="dynamic Lambda does not yet close Hubble tension",
)

v.record(
    "[-1,1]^4 has eight corners",
    2**4 == 8,
    computed=f"4D hypercube corner/vertex count = 2^4 = {2**4}",
    claimed="the eight corners of [-1,1]^4",
    detail="Expected direct counting fail.",
)
v.record(
    "the hypercube {-1,+1}^4 has eight vertices",
    len([(a, b, c, d) for a in (-1, 1) for b in (-1, 1) for c in (-1, 1) for d in (-1, 1)]) == 8,
    computed="{-1,+1}^4 has 16 vertices",
    claimed="eight vertices of the hypercube {-1,+1}^4",
    detail="Expected direct counting fail.",
)
v.record(
    "octonion basis identification follows from the 4-cube vertex count",
    False,
    computed="octonions have 8 basis elements, but the 4-cube has 16 vertices; no quotient or pairing map is supplied",
    claimed="natural identification between hypercube vertices and O basis",
    detail="Expected structural fail.",
)
v.record(
    "Euler exterior face derives Lambda0",
    False,
    computed="a planar cube net has one exterior face, but no measure-preserving map from that exterior face to the 4D corner residual 1-pi^2/32 is constructed",
    claimed="Euler forcing identifies the exterior face with Lambda0",
    detail="Expected proof-status fail.",
)
v.record(
    "folded cube-net exterior maps to the cube interior",
    False,
    computed="folding maps the six bounded squares to the cube surface; the unbounded exterior of the planar embedding is not itself a cube face or an interior cell",
    claimed="the exterior face is mapped to the interior of the cube upon folding",
    detail="Expected topology/folding fail.",
)
v.record(
    "tesseract Euler characteristic is unambiguously zero",
    False,
    computed="the boundary of a tesseract has chi=16-32+24-8=0, but the solid 4-cube is contractible with chi=1; the paper does not specify boundary vs solid",
    claimed="the tesseract (4-cube) has Euler characteristic chi=0",
    detail="Expected ambiguity fail.",
)
v.record(
    "static Lambda0 resolves the cosmological constant problem",
    "does not resolve" not in TEX,
    computed="the discussion explicitly says the old QFT vacuum-energy problem is not resolved",
    claimed="dark energy fully explained as Lambda0",
    detail="Expected status fail for any full-resolution reading.",
)

sys.exit(v.summary())
