#!/usr/bin/env python3
"""
verify_P015.py -- Paper 15: shadow universe / projection formula.

This verifier checks the master projection arithmetic, density integral, and
projection factors, and flags the unsupported bridge from 432/bifurcation to
the fine-structure constant and cosmological interpretation.
"""

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 as _BaseVerifier, CheckResult


class Verifier(_BaseVerifier):
    """Output-layer normalization only: same checks, modern [PASS]/[FAIL] 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)
        note, info = "", detail
        if not ok and "Expected" in detail:
            i = detail.find("Expected")
            note = " -- " + detail[i:]
            info = detail[:i].rstrip().rstrip(";")
        print(f"  [{'PASS' if ok else 'FAIL'}] {n:>2}. {label}{note}")
        if computed != "" or claimed != "":
            print(f"        computed: {computed}")
            print(f"        claimed : {claimed}")
        if info:
            print(f"        {info}")
        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 = Verifier("P015 -- Shadow Universe")

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

PI = math.pi
ALPHA_CODATA = 137.035999084
MASTER = (432.0 - PI / 2.0) / PI
DENSITY = 4.0 * PI**3 + PI**2 + PI
C4 = 4.0 / (3.0 * PI)


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


v.check("master projection formula", MASTER, 137.009871, rel=5e-9)
v.check("master projection error percent", abs(rel_percent(MASTER, ALPHA_CODATA)), 0.019, rel=4e-3)
v.check("density integral", DENSITY, 137.036304, rel=2e-9)
v.check("density integral error percent", abs(rel_percent(DENSITY, ALPHA_CODATA)), 0.000222, rel=3e-3)
v.check("B4 volume coefficient", PI**2 / 2.0, 4.93480220054, rel=1e-12)
v.check("S3 area coefficient", 2.0 * PI**2, 19.7392088022, rel=2e-12)
v.check("S3 area / B4 volume ratio at r=1", (2.0 * PI**2) / (PI**2 / 2.0), 4.0, rel=1e-14)
v.check("S3 projection factor c4", C4, 0.424, rel=1.1e-3)
v.check("432 factorization", 2**4 * 3**3, 432, rel=0)
v.check("432/pi versus 137", 432.0 / 137.0, PI, rel=4e-3)
v.check("dark-energy/baryon ratio", 68.0 / 5.0, ALPHA_CODATA / 10.0, rel=8e-3)

v.check(
    "S2 average absolute cosine",
    0.5,
    0.25,
    rel=1e-12,
    detail="Expected fail: (1/4pi) integral_S2 |cos theta| dOmega = 1/2, not 1/4; Cauchy's S/4 has an additional geometric convention.",
)
v.record(
    "division by pi follows from displayed projection factor",
    False,
    computed=f"displayed S3 average projection factor is 4/(3pi)={C4:.6f}, while the master equation projects by dividing by pi",
    claimed="factor pi is the projection ratio from S3 to R3",
    detail="Expected derivation mismatch.",
)
v.record(
    "pi/2 bifurcation correction is derived",
    False,
    computed="the paper interprets pi/2 as half of the density edge term, but no variational, projection, or boundary-splitting calculation forces subtracting it from 432 before division by pi",
    claimed="pi/2 emerges naturally from bifurcation at the B4/S3 boundary",
    detail="Expected proof-status fail.",
)
v.record(
    "source value 432 is derived from B4/S3 geometry",
    False,
    computed="432 is motivated by 16*27 and ancient-cosmology resonance, but no unique geometric map from B4/S3 to 16*27 is supplied",
    claimed="432 is the bulk source value arising from B4 geometry",
    detail="Expected derivation fail.",
)
v.record(
    "two alpha derivations are mutually consistent as derivations",
    False,
    computed=f"projection route gives {MASTER:.6f}, density route gives {DENSITY:.6f}; they differ by {DENSITY-MASTER:.6f}, and no theorem connects the two",
    claimed="two independent methods derive alpha inverse",
    detail="Expected consistency/bridge fail.",
)
v.record(
    "C o P = I cosmological operators are mathematically defined",
    False,
    computed="P and C are named as Big Bang projection and dark-energy collapse, but no state space, maps, or proof of inverse composition is defined",
    claimed="C o P = I describes a cosmic breathing cycle",
    detail="Expected operator-definition fail.",
)
v.record(
    "Lambda is derived from the return operator",
    False,
    computed="no calculation maps C to the observed cosmological constant scale or units",
    claimed="dark energy is the rate at which C acts",
    detail="Expected cosmology-derivation fail.",
)
v.record(
    "verification script is present",
    (ROOT / "projection_verification.py").exists(),
    computed="TOE/projection_verification.py not found",
    claimed="projection_verification.py available at repository",
    detail="Expected reproducibility fail.",
)

sys.exit(v.summary())
