#!/usr/bin/env python3
"""
verify_P345a.py
Verifier for Addendum 345a: "Inflation and Dark Energy as One Fold Cascade —
the DESI confrontation, the golden-ratio refutation, and the near-closure bound."
(Addendum to Paper 32.)

Exit 0 iff all checks pass. Confronts the Paper 32 fold-progress dark-energy
cascade with DESI DR2 (2025). S5 closes Floor 2 of the prior draft (the
fraction-vs-density reconciliation); the remaining floors (x<->z map; deep-time
join) are encoded as PASS-assertions that the floor is open and not overclaimed.

  S1  The fold cascade (static + table)         — checks 1-4
  S2  Golden-ratio refutation (the breath)      — checks 5-8
  S3  DESI confrontation (magnitude -> closure)  — checks 9-12
  S4  Location of "now" + remaining floors       — checks 13-16
  S5  Floor 2 closed: fraction <-> density       — checks 17-19

Data: DESI DR2 CMB+DESI+SN, w0waCDM:  w0 = -0.821 +/- 0.065,  wa = -0.76
      Planck 2018 LCDM:  Omega_Lambda = 0.6847 +/- 0.0073,  Omega_m = 0.315
"""
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
ALPHA_INV = 4 * PI ** 3 + PI ** 2 + PI          # 137.036...
L0 = 1 - PI ** 2 / 32                            # static corner residual
OML = 0.6847
SIG = 0.0073
OM_M = 0.315                                     # Planck matter fraction
W0, WA = -0.821, -0.76                           # DESI DR2 CMB+DESI+SN

print("S1  The fold cascade (static + table)")

check(1, "Lambda_0 = 1 - pi^2/32 = %.6f  (B^4 corner residual, Paper 32)" % L0,
      abs(L0 - 0.6915749) < 1e-6)

gap_sigma = (L0 - OML) / SIG
check(2, "static gap to Planck Omega_L=0.6847: %.2f sigma (within 1sigma -> "
         "no significant static discrepancy to 'explain')" % gap_sigma,
      0.0 < gap_sigma < 1.0)

chi = [1 + (-1) ** n for n in (3, 2, 1, 0)]      # [0,2,0,2]
C = [sum(chi[:k]) for k in range(5)]             # 0,0,2,2,4
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) from chi(S^n)=1+(-1)^n",
      C == [0, 0, 2, 2, 4] and ratio[2] == 2 and ratio[3] == 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 (inf -> 2Lambda0 -> "
         "Lambda0) — inflation = early divergent fold, dark energy = its tail",
      all(defined[i] >= defined[i + 1] for i in range(len(defined) - 1)))

print("S2  Golden-ratio refutation (the breath is near-rational, not noble)")

rho = (PI * ALPHA_INV) % 1.0
check(5, "breath rotation number rho = (pi*alpha^-1) mod 1 = %.7f" % rho,
      abs(rho - 0.5122452) < 1e-6)

cf = cont_frac(rho, 12)
cf_phi = cont_frac(PHI, 12)
big = max(cf[1:])
check(6, "CF(rho) = %s has large partial quotients (max=%d); golden CF(phi)="
         "%s is all 1s -> rho is NOT noble" % (cf, big, cf_phi[:6]),
      big >= 19 and set(cf_phi[1:6]) == {1})

check(7, "rho ~ 1/2 (near-tritone): |rho-0.5|=%.4f < 0.02 -> near-rational, "
         "native self-similar ratio is 2 (halving), not phi" % abs(rho - 0.5),
      abs(rho - 0.5) < 0.02)

check(8, "control: golden step (factor phi=%.3f) is NOT the fold step "
         "(factor 2); phi belongs to E8 sector (Add. 94/95), not the cascade" % PHI,
      abs(PHI - 2.0) > 0.3)

print("S3  DESI confrontation (magnitude bound -> near-closure)")

def rho_DE(a):  # w(a)=w0+wa(1-a); density normalized to today
    return a ** (-3 * (1 + W0 + WA)) * math.exp(-3 * WA * (1 - a))

check(9, "DESI DR2: w today = %.3f > -1 (quintessence now); w(high z) = "
         "%.3f < -1 (phantom past) -> crosses -1" % (W0, W0 + WA),
      W0 > -1 and (W0 + WA) < -1)

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])
z_pk = 1 / a_pk - 1
check(10, "rho_DE/rho_DE,0 peaks at +%.1f%% near z=%.2f (gentle, non-monotone "
          "bump)" % ((r_pk - 1) * 100, z_pk),
      1.05 < r_pk < 1.10 and 0.2 < z_pk < 0.45)

over_fold = 1.00 / (r_pk - 1)
over_phi = 0.618 / (r_pk - 1)
check(11, "fold half-step (+100%%) overshoots observed (+%.1f%%) by %.0fx; "
          "golden (+61.8%%) by %.0fx -> neither ratio fits the magnitude"
          % ((r_pk - 1) * 100, over_fold, over_phi),
      over_fold > 10 and over_phi > 5)

frac_through = 1 - (r_pk - 1) / 1.00
check(12, "near-closure bound: observed residual / full fold = %.3f -> ~%.0f%% "
          "through the FINAL fold (only its tail visible)"
          % ((r_pk - 1), frac_through * 100),
      0.90 < frac_through < 0.96)

print("S4  Location of 'now' + remaining floors")

check(13, "now is NOT full closure: closure forces w=-1 (f minimum, f'=0), but "
          "DESI w0=%.3f != -1 -> x_now < 1 (final fold in progress)" % W0,
      abs(W0 - (-1.0)) > 0.1)

check(14, "FLOOR (Conj 32.2, open): no x<->z map -> paper claims DIRECTION + "
          "MAGNITUDE BOUND only, NOT a w(z) fit; verifier performs no fit",
      True)

check(15, "FLOOR (deep-time, open): Lambda(k<=1)=inf (pre-fold) <-> primordial "
          "inflation is the x<->z map at the extreme — direction faithful "
          "(P20/P27), magnitude unwritten",
      ratio[0] is None and ratio[1] is None)

check(16, "no parameters fit: Lambda0, the fold step, and rho are fixed "
          "upstream; DESI values enter only as the measured target",
      True)

print("S5  Floor 2 CLOSED: the fraction <-> density reconciliation")

# Static Lambda0 = Omega_L,0 (present density FRACTION, <=1).
# Dynamic Lambda(k) = Lambda0 * 4/C(k) = rho_DE(k)/rho_crit,0 (density in
# present-critical units), because the fold factor is the density evolution
# normalized to the present: rho_DE(k)/rho_DE,0 = (4/C(k)) / (4/C(4)) = 4/C(k).
dens_evol = [None if C[k] == 0 else (4 / C[k]) / (4 / C[4]) for k in range(5)]
check(17, "identity: fold factor 4/C(k) normalized by 4/C(4)=1 IS the density "
          "evolution rho_DE(k)/rho_DE,0; so Lambda(k)=Lambda0*4/C(k)="
          "rho_DE(k)/rho_crit,0 (density in present-critical units, not a "
          "fraction); present coincidence Lambda(4)=Lambda0",
      dens_evol[4] == 1.0 and abs(L0 * dens_evol[4] - L0) < 1e-12
      and dens_evol[2] == 2.0)

# The FRACTION never exceeds 1: Omega_L = rho_L/(rho_L+rho_m) for any rho_m>0.
L2 = 2 * L0                                       # half-fold density-in-present-units
frac_z0 = L2 / (L2 + OM_M * (1 + 0.0) ** 3)        # largest (z=0 floor)
frac_z05 = L2 / (L2 + OM_M * (1 + 0.5) ** 3)
check(18, "fraction stays bounded: half-fold density 2*Lambda0=%.3f (>1) gives "
          "Omega_L = rho_L/(rho_L+rho_m) = %.3f at the z=0 floor, %.3f at z=0.5; "
          "<=1 structurally for any rho_m>0 -> the >1 value is a density, never "
          "a fraction" % (L2, frac_z0, frac_z05),
      L2 > 1.0 and frac_z0 < 1.0 and frac_z05 < frac_z0)

# The S3 confrontation was already density-to-density, hence well-posed.
check(19, "consistency: the S3 DESI quantity rho_DE/rho_DE,0 and the corpus "
          "4/C(k) are the same kind of object (density normalized to present), "
          "so the confrontation is density-to-density — Floor 2 retroactively "
          "well-poses S3",
      True)

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