#!/usr/bin/env python3
"""
verify_P014.py -- Paper 14: cosmic breathing and the 432 correspondence.

This verifier checks the displayed 432/alpha/pi numerics and flags the places
where approximate cultural/numerological correspondences are promoted to
derived physics.
"""

from __future__ import annotations

import math
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))

PASS = FAIL = 0
_N = 0


def check(n, desc, cond):
    global PASS, FAIL
    ok = bool(cond)
    PASS += ok
    FAIL += not ok
    print(f"  [{'PASS' if ok else 'FAIL'}] {n:>2}. {desc}")
    return ok


class Verifier:
    """Output adapter: identical check semantics, modern [PASS]/[FAIL] format."""

    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_detail = f"abs err={abs(computed - claimed):.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, detail, err_detail)

    def record(self, label, ok, computed="", claimed="", detail="", err_detail=""):
        global _N
        _N += 1
        desc = label + (f" -- {detail}" if detail else "")
        check(_N, desc, ok)
        if computed != "" or claimed != "":
            print(f"        computed: {computed}")
            print(f"        claimed : {claimed}")
        if err_detail:
            print(f"        {err_detail}")
        return ok

    def summary(self):
        print(f"\n{'='*60}\nRESULT: {PASS} PASS / {FAIL} FAIL")
        return 1 if FAIL else 0


v = Verifier("P014 -- Cosmic Breathing")

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

PI = math.pi
MU0 = 4.0 * PI**3 + PI**2 + PI
ALPHA = 1.0 / MU0
KAPPA = ALPHA ** 1.25
BREATH = PI * MU0

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


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


v.check("alpha inverse monad", MU0, 137.036, rel=3e-6)
v.check("Level 1 pi alpha inverse", BREATH, 430.51, rel=6e-6)
v.check("Level 1 gap to 432 percent", (432.0 - BREATH) / 432.0 * 100.0, 0.35, rel=2e-2)
v.check("Level 2 pi^2 alpha inverse", PI**2 * MU0, 1352.5, rel=7e-6)
v.check("Level 3 pi^3 alpha inverse", PI**3 * MU0, 4249.0, rel=4e-6)
v.check("432 factorization 16*27", 16 * 27, 432, rel=0)
v.check("432 factorization 2^4*3^3", 2**4 * 3**3, 432, rel=0)
v.check("mahakalpa factorization", 432.0 * 720.0 * 1e9, 311.04e12, rel=1e-12)
v.check("6 factorial", math.factorial(6), 720, rel=0)
v.check("omega1 from kappa", PI * math.sqrt(1.0 - KAPPA), 3.138, rel=8e-5)
v.check("oscillation floor 4pi", 4.0 * PI, 12.566, rel=4e-5)
v.check("E_self", E_SELF, 13.177, rel=3e-5)
v.check("oscillation gap", E_SELF - 4.0 * PI, 0.611, rel=2e-3)
v.check("432/pi^3", 432.0 / PI**3, 13.93, rel=2e-4)
v.check("432/pi^3 gap to 14 percent", abs(100.0 * (432.0 / PI**3 - 14.0) / 14.0), 0.48, rel=3e-3)
v.check("14*71 + 15*4*0.4", 14.0 * 71.0 + 15.0 * 4.0 * 0.4, 1018.0, rel=0)
v.record(
    "manvantara arithmetic correction is present",
    "total is 1018, not 1000" in TEX,
    computed="14*71 + 15*4*0.4 = 1018",
    claimed="paper corrects the earlier 1000-cycle arithmetic",
)

v.check(
    "432/430.51 ratio equals 1+kappa^0.6",
    432.0 / BREATH,
    1.0 + KAPPA**0.6,
    rel=1e-3,
    detail="Expected fail: kappa^0.6 is about 0.02497, while the ratio excess is about 0.00346.",
)
v.check(
    "432/pi^3 matches E_self",
    432.0 / PI**3,
    E_SELF,
    rel=1e-2,
    detail="Expected fail: the gap is about 5.7%, much looser than the 14 comparison.",
)
v.check(
    "14 is the nearest integer approximation to E_self",
    round(E_SELF),
    14,
    rel=0,
    detail="Expected fail: E_self≈13.177 rounds to 13, not 14.",
)
v.check(
    "14 is close to E_self at the same level as 432/pi^3",
    abs(pct(14.0, E_SELF)),
    abs(pct(14.0, 432.0 / PI**3)),
    rel=5e-1,
    detail="Expected fail: 14 is ~6.25% above E_self but only ~0.48% above 432/pi^3.",
)
v.record(
    "breathing period follows from C o P = I",
    False,
    computed="the proof selects omega_breath = omega1/(pi*alpha^-1) as the natural choice; no dynamics derive that divisor from C o P = I",
    claimed="T_breath = pi*alpha^-1 from anti-collapse dynamics",
    detail="Expected derivation fail.",
)
v.record(
    "432=16*27 is evidence beyond a numeric encoding",
    False,
    computed="16 and 3 are identified with density coefficients, but no independent map from Hindu time-cycle units to those coefficients is derived",
    claimed="432 encodes bulk coefficient times boundary coefficient cubed",
    detail="Expected proof-status fail.",
)
v.record(
    "ancient contemplative access is mathematically verifiable here",
    False,
    computed="the TeX provides no historical source analysis or testable mathematical mechanism for transmission",
    claimed="ancient cosmological intuitions encoded geometric truths",
    detail="Expected non-verifiable claim.",
)
v.record(
    "dimensional lifting by pi is uniquely derived",
    False,
    computed="multiplication by pi is proposed as a hierarchy operation, but uniqueness is not proved from an operator or dimensional-analysis rule",
    claimed="pi*alpha^-1 is the unique one-dimension lift",
    detail="Expected proof-status fail.",
)

sys.exit(v.summary())
