#!/usr/bin/env python3
"""
verify_P033.py -- Paper 33: self-intersection weights and monad closure.

Checks the screened-weight arithmetic and flags the places where the geometric
interpretation is stronger than the formulas prove.
"""

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 Verifier, CheckResult


class ModernVerifier(Verifier):
    """Local adapter: modern check-line output format. Tolerance logic is
    inherited unchanged from verify_common.Verifier; only printing differs.
    Computed/claimed values stay as indented info lines."""

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

    def record(self, label, ok, computed="", claimed="", detail=""):
        self.results.append(CheckResult(label, ok, computed, claimed, detail))
        status = "PASS" if ok else "FAIL"
        desc = f"{label} -- {detail}" if detail else label
        print(f"  [{status}] {len(self.results):>2}. {desc}")
        if computed != "" or claimed != "":
            print(f"          computed: {computed}")
            print(f"          claimed : {claimed}")
        return ok

    def summary(self) -> int:
        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("P033 -- Self-Intersection Monad")

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

PI = math.pi
ALPHA_INV_CODATA = 137.035999084


def c_count(d: int) -> int:
    k = d + 1
    return k ** max(d - 1, 1)


def screened_weight(d: int) -> float:
    return c_count(d) / (d + 1)


v.record("TeX source is present", "Self-Intersection Weights" in TEX)

counts = [c_count(d) for d in (1, 2, 3)]
weights = [screened_weight(d) for d in (1, 2, 3)]
v.record("self-intersection counts", counts == [2, 3, 16], computed=counts, claimed="[2, 3, 16]")
v.record("screened weights", weights == [1.0, 1.0, 4.0], computed=weights, claimed="[1, 1, 4]")
for d in (1, 2, 3):
    k = d + 1
    v.check(f"screened formula d={d}", screened_weight(d), k ** max(d - 2, 0), rel=0)

alpha_geom = sum(screened_weight(d) * PI**d for d in (1, 2, 3))
v.check("screened alpha sum", alpha_geom, 4.0 * PI**3 + PI**2 + PI, rel=1e-15)
v.check("screened alpha numerical value", alpha_geom, 137.036304, rel=3e-9)

for d in (1, 2, 3):
    k = d + 1
    v.check(
        f"corrected complement identity d={d}",
        c_count(d) * k ** min(4 - d, 2),
        k**3,
        rel=0,
    )
    v.check(
        f"three-factor exponent sum d={d}",
        max(d - 2, 0) + 1 + min(4 - d, 2),
        3,
        rel=0,
    )

v.record(
    "Nicomachus cube sequence values",
    [(d + 1) ** 3 for d in (1, 2, 3)] == [8, 27, 64],
    computed=[(d + 1) ** 3 for d in (1, 2, 3)],
    claimed="[8, 27, 64]",
)
v.check("P32 Lambda0 companion value", 1.0 - PI**2 / 32.0, 0.691575, rel=1e-6)

v.record(
    "original Hopf factorisation statement is literally true",
    False,
    computed="for d=1, k^0*k^1*k^2=8 while c_1=2; for d=2, product=27 while c_2=3; for d=3, product=64 while c_3=16",
    claimed="c_d = k^max(d-2,0) * k^1 * k^min(4-d,2)",
    detail="Expected fail: the proof itself notices and corrects this.",
)
v.record(
    "pi^d is the exact volume of S^{d-1} for d=1,2,3",
    False,
    computed="Vol(S0)=2, Vol(S1)=2*pi, Vol(S2)=4*pi; unit ball volumes are 2, pi, 4*pi/3, not pi^d",
    claimed="pi^d measures the geometric volume of S^{d-1}; for d in {1,2,3}, pi^d is the exact measure",
    detail="Expected geometric-measure fail.",
)
v.record(
    "Hopf fibration absorption is derived by the arithmetic",
    False,
    computed="division by k comes from integrating x^d over [0,1]; no explicit Hopf action on the self-intersection counts is constructed",
    claimed="Hopf fibration absorbs one power of k from the self-intersection count",
    detail="Expected interpretation/proof gap.",
)
v.record(
    "fine-structure constant is exactly derived as physical alpha inverse",
    False,
    computed=f"geometric value={alpha_geom:.12f}, CODATA alpha^-1={ALPHA_INV_CODATA:.12f}, difference={alpha_geom-ALPHA_INV_CODATA:.6g}",
    claimed="alpha^-1 = 4*pi^3 + pi^2 + pi",
    detail="Expected precision/equality fail.",
)
v.record(
    "Nicomachus sum-of-cubes identity is used",
    False,
    computed="the paper uses the cubes 8,27,64, but not the identity sum_{j=1}^n j^3=(sum_{j=1}^n j)^2 in a derivation",
    claimed="Nicomachus connection explains the closure",
    detail="Expected scope fail: this is a cube-sequence analogy, not a use of the identity.",
)
v.record(
    "self-intersection counts are independently derived in P33",
    False,
    computed="the counts c_d are imported from Paper 08; P33 verifies consequences of those counts but does not derive the observer-projection counting itself",
    claimed="new derivation from self-intersection counts",
    detail="Expected dependency-status fail.",
)
v.record(
    "Paper 32/P33 circuit is fully established",
    False,
    computed="the companion P32 dark-energy result has its own structural caveats; P33 only shares B4 inputs and does not prove mutual derivability",
    claimed="combined with Paper 32, the result completes a circuit",
    detail="Expected cross-paper overstatement.",
)

sys.exit(v.summary())
