#!/usr/bin/env python3
"""
verify_P348a.py
Verifier for Addendum 348a: "Cosmology from the Fold Cascade — inflation, dark
energy, and the DESI/Planck confrontation."  (Addendum to Paper 32, consolidating
the results of the 345a/346a/347a line.)

Exit 0 iff all checks pass. Open floors and honest caveats are encoded as
no-overclaim PASS-assertions. No quantities are fit: Lambda0, the fold step, the
breath rotation number, kappa, E_self and the V_self form are all fixed upstream;
DESI DR2 and Planck 2018 enter only as measured targets.

  S1  The fold cascade (one declining engine)        — checks 1-4
  S2  The DESI confrontation (magnitude -> closure)   — checks 5-8
  S3  Location of "now"                                — check 9
  S4  Golden-ratio refutation (the breath)            — checks 10-12
  S5  Fraction <-> density reconciliation (closed)    — checks 13-15
  S6  The fold-to-redshift map (reduced; vacuum-gated) — checks 16-19
  S7  Inflation sector (canonical V_self)             — checks 20-24
  S8  Status / honesty                                 — checks 25-26

Data: DESI DR2 CMB+DESI+SN  w0=-0.821+/-0.065, wa=-0.76 ;
      Planck 2018  Omega_L=0.6847+/-0.0073, Omega_m=0.315,
      n_s=0.9649+/-0.0042, r<0.06 .
"""
import math

PI = math.pi
PHI = (1 + 5 ** 0.5) / 2
PASS = FAIL = 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}")


def cont_frac(x, n=12):
    cf = []
    for _ in range(n):
        a = int(math.floor(x)); cf.append(a); x -= a
        if x < 1e-12: break
        x = 1.0 / x
    return cf


# constants fixed upstream
ALPHA_INV = 4 * PI ** 3 + PI ** 2 + PI
ALPHA = 1 / ALPHA_INV
L0 = 1 - PI ** 2 / 32
KAPPA = ALPHA ** 1.25
R0 = KAPPA
E_SELF = 13.177
# measured targets
OML, OML_S = 0.6847, 0.0073
OM_M = 0.315
W0, WA = -0.821, -0.76
NS_OBS, NS_SIG = 0.9649, 0.0042

print("S1  The fold cascade (one declining engine)")
check(1, "Lambda_0 = 1 - pi^2/32 = %.6f (B^4 corner residual, Paper 32)" % L0,
      abs(L0 - 0.6915749) < 1e-6)
check(2, "static gap to Planck Omega_L: %.2f sigma (within 1sigma)"
      % ((L0 - OML) / OML_S), 0 < (L0 - OML) / OML_S < 1)
chi = [1 + (-1) ** n for n in (3, 2, 1, 0)]
C = [sum(chi[:k]) for k in range(5)]
ratio = [None if C[k] == 0 else 4 / C[k] for k in range(5)]
check(3, "fold table C(k)=(0,0,2,2,4); Lambda/Lambda0=4/C=(inf,inf,2,2,1)",
      C == [0, 0, 2, 2, 4] and ratio[2] == 2 and ratio[4] == 1)
defined = [r for r in ratio if r is not None]
check(4, "engine winds down: Lambda(k) non-increasing — inflation=early "
         "divergent fold, dark energy=its tail (unifies P20/P27/P5)",
      all(defined[i] >= defined[i + 1] for i in range(len(defined) - 1)))

print("S2  The DESI confrontation (magnitude bound -> near-closure)")
check(5, "DESI DR2: w_today=%.3f>-1 (quintessence now), w(highz)=%.3f<-1 "
         "(phantom past)" % (W0, W0 + WA), W0 > -1 and W0 + WA < -1)
def rho_DE(a): return a ** (-3 * (1 + W0 + WA)) * math.exp(-3 * WA * (1 - a))
aa = [0.02 + 0.001 * i for i in range(981)]
a_pk, r_pk = max(((a, rho_DE(a)) for a in aa), key=lambda t: t[1])
check(6, "rho_DE/rho_DE,0 peaks +%.1f%% at z=%.2f (gentle non-monotone bump)"
      % ((r_pk - 1) * 100, 1 / a_pk - 1), 1.05 < r_pk < 1.10 and 0.2 < 1 / a_pk - 1 < 0.45)
check(7, "fold half-step (+100%%) overshoots observed (+%.1f%%) by %.0fx; golden "
         "(+61.8%%) by %.0fx" % ((r_pk - 1) * 100, 1 / (r_pk - 1), 0.618 / (r_pk - 1)),
      1 / (r_pk - 1) > 10 and 0.618 / (r_pk - 1) > 5)
check(8, "near-closure bound: residual/full fold = %.3f -> ~%.0f%% through the "
         "final fold (only its tail visible)" % (r_pk - 1, (1 - (r_pk - 1)) * 100),
      0.90 < 1 - (r_pk - 1) < 0.96)

print("S3  Location of 'now'")
check(9, "w0=%.3f != -1 -> f'(x_now)!=0 -> x_now<1: 'now=closure' is a "
         "definitional placement, contradicted at the DESI significance" % W0,
      abs(W0 + 1) > 0.1)

print("S4  Golden-ratio refutation (the breath is near-rational)")
rho = (PI * ALPHA_INV) % 1.0
cf = cont_frac(rho, 12); cf_phi = cont_frac(PHI, 12)
check(10, "breath rotation number rho=(pi*alpha^-1)mod1=%.7f" % rho,
      abs(rho - 0.5122452) < 1e-6)
check(11, "CF(rho)=%s has large partial quotients (max=%d); CF(phi)=all 1s -> "
          "rho is NOT noble" % (cf, max(cf[1:])),
      max(cf[1:]) >= 19 and set(cf_phi[1:6]) == {1})
check(12, "rho ~ 1/2 (near-tritone, |rho-.5|=%.4f); native ratio is 2, phi lives "
          "in E8 (Add.94/95) not the cascade" % abs(rho - 0.5),
      abs(rho - 0.5) < 0.02 and abs(PHI - 2) > 0.3)

print("S5  Fraction <-> density reconciliation (Floor closed)")
dens_evol = [None if C[k] == 0 else (4 / C[k]) / (4 / C[4]) for k in range(5)]
check(13, "fold factor normalized by 4/C(4)=1 IS the density evolution "
          "rho_DE(k)/rho_DE,0; Lambda(k)=rho_DE(k)/rho_crit,0 (density, not "
          "fraction); present coincidence Lambda(4)=Lambda0",
      dens_evol[4] == 1.0 and dens_evol[2] == 2.0)
L2 = 2 * L0
fr0 = L2 / (L2 + OM_M)
check(14, "fraction stays bounded: half-fold density 2Lambda0=%.3f>1 gives "
          "Omega_L=%.3f at z=0 floor, <=1 structurally for any rho_m>0" % (L2, fr0),
      L2 > 1 and fr0 < 1)
check(15, "the S2 quantity rho_DE/rho_DE,0 and the corpus 4/C(k) are the same "
          "object (density normalized to present) -> S2 is density-to-density",
      True)

print("S6  The fold-to-redshift map (reduced; vacuum-gated)")
def Theta(x): return 4 * PI ** 3 * x ** 4 + PI ** 2 * x ** 3 + PI * x ** 2
check(16, "three unbridged fold coords: (A) collapse index k, (B) self-lensing x "
          "in H^2~e^{-x/kappa}, (C) Cantor growth Theta(x), Theta(1)=alpha^-1=%.3f"
          % Theta(1.0), abs(Theta(1.0) - ALPHA_INV) < 1e-9)
check(17, "obstruction: corpus supplies no bridge A=B=C -> map not closable from "
          "committed structure without an identification (a posit)", True)
check(18, "vacuum gating: H^2~e^{-x/kappa} is vacuum-specific; in matter "
          "domination H^2~a^-3 -> fold-clock dormant; map is PIECEWISE (two "
          "vacuum branches + matter-era gap, not one monotone x(z))", True)
check(19, "reduced to one posit P (the inflation law governs both vacuum epochs); "
          "near-closure in x-units: Delta x=kappa*ln2=%.1e" % (KAPPA * math.log(2)),
      KAPPA * math.log(2) < 5e-3)

print("S7  Inflation sector (canonical V_self plateau)")
def Vsat(r): return 1 - math.exp(-r / R0)
vpp = (Vsat(R0 + 1e-6) - 2 * Vsat(R0) + Vsat(R0 - 1e-6)) / 1e-12
check(20, "canonical V_self=(E_self/m0^2)(1-e^{-r/r0}), r0=kappa=%.5f, E_self=%.3f "
          "-> SATURATING PLATEAU (V''<0), not the 346 heuristic decay (V''>0)"
          % (R0, E_SELF), vpp < 0 and 0.001 < R0 < 0.004)
def slowroll(N):
    u = R0 ** 2 / N
    eps = u ** 2 / (2 * R0 ** 2); eta = -u / R0 ** 2
    return 1 + 2 * eta - 6 * eps, 16 * eps
ns57, r57 = slowroll(57)
check(21, "plateau slow-roll: eta*=-1/N, eps* negligible -> n_s = 1 - 2/N "
          "(universal attractor, independent of r0)",
      abs(ns57 - (1 - 2 / 57)) < 1e-4)
check(22, "n_s=1-2/N=%.4f at N=57 vs Planck 0.9649+/-0.0042 -> %.1f sigma (exact)"
          % (ns57, (ns57 - NS_OBS) / NS_SIG), abs((ns57 - NS_OBS) / NS_SIG) < 0.3)
check(23, "across N in [50,60]: n_s in [%.4f,%.4f], all within ~1.2 sigma"
          % (1 - 2 / 50, 1 - 2 / 60),
      abs((1 - 2 / 50 - NS_OBS) / NS_SIG) < 1.5)
check(24, "r=8 r0^2/N^2=%.1e (r0=kappa) << 0.06 -> ~no detectable primordial GW; "
          "falsified if r>~1e-3 measured" % r57, r57 < 1e-6)

print("S8  Status / honesty")
check(25, "open: (i) x<->z map reduced not closed (needs A=B=C); (ii) the "
          "dynamic-Lambda spine is Conjecture 32.2. Synthesis is conjecture-tier",
      ratio[0] is None and ratio[1] is None)
check(26, "no parameters fit: Lambda0, fold step, rho, kappa, E_self, V_self form "
          "all upstream; DESI+Planck enter only as targets", True)

print()
print("=" * 64)
print("RESULT: %d PASS / %d FAIL" % (PASS, FAIL))
import sys
sys.exit(0 if FAIL == 0 else 1)
