#!/usr/bin/env python3
"""LENS 3 independent verification (third pass). Fresh implementation, fresh seed.
Checks: (1) App CE's own arithmetic; (2) G8d NULL-C/NULL-D numbers; (3) the
specific per-row attacks (a0 window vs target uncertainty; a0-H0 dependency;
sin2b downstream of fitted integers; s2w rational menu); (4) an independent
'middle path' repricing starting from CE and applying ONLY corpus-grounded
charges (AO E.1 postulate, AU 3/135, target-uncertainty windows).
"""
import math, json
import numpy as np
from statistics import NormalDist

nd = NormalDist()
def Z(p): return nd.inv_cdf(1.0 - p) if 0 < p < 1 else 0.0

out = {}

# ---------------------------------------------------------------- 1. App CE own arithmetic
ce_p6 = dict(s2w=0.004, a0=0.005, ns=0.004, Ochi_Ob=0.009, th12=0.074, s2b=0.031)
P6 = math.prod(ce_p6.values())
floor_rows = ('s2w', 'a0', 'th12', 's2b')
P4 = math.prod(ce_p6[k] for k in floor_rows)
out['CE_arithmetic'] = {
    'P6_product_of_stated_ps': P6, 'Z6': Z(P6), 'CE_claims': '1.4e-12 -> 7.1 sigma',
    'P4_floor': P4, 'Z4': Z(P4), 'CE_claims_floor': '3e-8 -> 5.5 sigma',
    'P6_looser_3x': P6 * 3**6, 'Z6_looser': Z(P6 * 3**6), 'CE_claims_looser': '1.0e-9 -> 6.1 sigma',
    'P4_looser_3x': P4 * 3**4, 'Z4_looser': Z(P4 * 3**4), 'CE_claims_floor_looser': '~4.6 sigma'}

# recompute the delta_i themselves from CE's table
deltas = dict(s2w=abs(3/13-0.23122)/0.23122, a0=abs(1.197-1.20)/1.20,
              ns=abs(0.9667-0.9649)/0.9649, Ochi=abs(5.333-5.357)/5.357,
              th12=abs(0.3184-0.307)/0.307, s2b=abs(0.719-0.708)/0.708)
out['CE_deltas_recomputed'] = {k: round(v,5) for k,v in deltas.items()}
P6_exact = math.prod(min(1,2*d) for d in deltas.values())
P4_exact = 2*deltas['s2w']*2*deltas['a0']*2*deltas['th12']*2*deltas['s2b']
out['CE_arithmetic']['P6_from_2delta_exact'] = (P6_exact, Z(P6_exact))
out['CE_arithmetic']['P4_from_2delta_exact'] = (P4_exact, Z(P4_exact))

# ---------------------------------------------------------------- 2. G8d NULL-C check
p_cons = (1/12)*(3/135)*0.136
p_mod  = (1/56)*((3/135)*0.074)*0.136
out['G8d_NULLC_check'] = {'p_cons': p_cons, 'Z_cons': Z(p_cons),
                          'p_mod': p_mod, 'Z_mod': Z(p_mod),
                          'G8d_claims': '2.52e-4/3.48s and 3.99e-6/4.47s'}

# ---------------------------------------------------------------- 3. NULL-D order-statistics MC (fresh seed, fresh impl)
rng = np.random.default_rng(777001)
def sel_p(T, M, k=3, nsim=4_000_000):
    u = rng.random((nsim, M))
    u.sort(axis=1)
    return float((np.prod(u[:, :k], axis=1) <= T).mean())
out['NULLD_check'] = {}
for tag, T in (('cons', p_cons), ('mod', p_mod)):
    for M in (12, 20):
        out['NULLD_check'][f'{tag}_M{M}'] = sel_p(T, M)
# G8d claims: cons_M12 0.227, cons_M20 0.456, mod_M12 0.0164, mod_M20 0.0488

# ---------------------------------------------------------------- 4. Per-row attacks re-derived
# (a) a0 row: CE prices at 2*0.25% = 0.005 but empirical a0 = (1.20 +/- 0.02_stat +/- 0.24_syst)e-10
#     (McGaugh RAR). Landing closer than the target is known cannot add evidence.
alpha = 1/137.035999084
H0_dfd, H0_shoes = 72.09, 73.04            # km/s/Mpc
kmsmpc = 1000/3.0857e22
a0_dfd  = 2*math.sqrt(alpha)*2.998e8*H0_dfd*kmsmpc
a0_meas = 2*math.sqrt(alpha)*2.998e8*H0_shoes*kmsmpc
out['a0_row'] = {
    'a0_with_DFD_H0': a0_dfd, 'a0_with_SH0ES_H0': a0_meas,
    'frac_agreement_if_measured_H0_used': abs(a0_meas-1.20e-10)/1.20e-10,
    'honest_window_stat_only_2sigfrac': 2*(0.02/1.20),
    'note': 'CE 0.005 credits sub-target-uncertainty closeness AND silently uses DFD H0 (a 2nd alpha-ladder output) inside the row'}

# (b) s2w rational-menu recount (independent of E5's implementation)
meas = 0.23122; win = abs(3/13-meas)
def menu(qmax, lo=0.15, hi=0.35):
    tot=hit=0
    for q in range(2,qmax+1):
        for p in range(1,q):
            if math.gcd(p,q)==1 and lo<=p/q<=hi:
                tot+=1; hit+= (abs(p/q-meas)<=win)
    return hit,tot
out['s2w_menu'] = {f'q<={q}': menu(q) for q in (13,20,30,60)}
out['s2w_menu']['hostile_ratio'] = max(h/t for h,t in (menu(q) for q in (13,20,30,60)))

# (c) sin2b row: downstream of 4 selected integers (31,108,43/2,49) + Postulate E.1
#     (AO status: 'a new structural assumption ... not derived'; antitheorem: no apex forcing).
#     If the 4 apex coords are selected/fitted, sin2b is a function of them = consistency check.
out['s2b_row'] = 'NOT cleanly forced by corpus own account (AO antitheorem L96-104 + E.1 status). CE floor claim "verified for the six" contradicted.'

# ---------------------------------------------------------------- 5. Independent MIDDLE-PATH repricing
# Start from CE, apply ONLY corpus-grounded charges; keep th12 at hostile ansatz-menu level.
mid = {}
mid['step0_CE_floor4'] = (P4_exact, Z(P4_exact))
p3 = P4_exact / (2*deltas['s2b'])                       # drop sin2b (E.1 selection)
mid['step1_drop_s2b'] = (p3, Z(p3))
p3b = 2*deltas['s2w'] * 0.033 * 2*deltas['th12']        # a0 window -> 2*stat-unc of target
mid['step2_a0_honest_window'] = (p3b, Z(p3b))
p3c = out['s2w_menu']['hostile_ratio'] * 0.033 * 2*deltas['th12']   # menu-charge s2w
mid['step3_menu_s2w'] = (p3c, Z(p3c))
p3d = p3c / (2*deltas['th12']) * (5/14)                 # th12 -> ansatz-menu 5/14
mid['step4_menu_th12'] = (p3d, Z(p3d))
# add-back: Omega_chi h^2 = 0.118 (new CS-Casimir engine) at G8d hostile 0.136
p4e = p3d * 0.136
mid['step5_add_Ochi_hostile'] = (p4e, Z(p4e))
out['middle_path'] = mid

# G8d flagship+th12 variant (does readmitting th12 change the hostile band?)
pC_th12 = p_cons * (5/14)
out['NULLC_plus_th12'] = (pC_th12, Z(pC_th12))

print(json.dumps(out, indent=1, default=str))
with open('verify3x/lens3_results.json','w') as f:
    json.dump(out, f, indent=1, default=str)
