#!/usr/bin/env python3
"""E6 SYNTHESIS — fold SK1 (enlarged space) + SK2 (selection null, hit recount)
into the final conditional no-coincidence theorem. Every number in the
final synthesis comes from this script. Honesty-guard maximal: worst case headlines.
"""
import json, math
import numpy as np
from statistics import NormalDist

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

out = {}

# ---------------------------------------------------------------- 1. SPACE
# E2 conservative core 185,472; SK1 multiplier x43,200
# (surfaces x10, lens quotients x12, dimX x3, formula grammar x6,
#  Wolfenstein basis x3 on CKM, 57-subtraction x2, AU 9->30 x(10/3))
sk1_mult = 10*12*3*6*3*2*(30/9)
core_base = 64
core_cons_E2 = 185_472
core_cons = core_cons_E2 * sk1_mult
full_bits_E2 = 4.75e7
full_cons = full_bits_E2 * sk1_mult
out['space'] = dict(baseline_core=core_base,
                    conservative_core=core_cons,
                    conservative_full_bits=full_cons,
                    sk1_multiplier=sk1_mult)

# ---------------------------------------------------- 2. ALPHA-LADDER LEMMA (SK1 attack 8)
# Imported from E5's artifact (re-verification C9: no hard-coding on re-run). The
# authoritative per-ladder false-match probability and ladder count are written
# by E5_skeptic_attacks.py into E5_skeptic_attacks.json (attack8_ladder_budget);
# E5_results.json (the E5b/recount output) does not carry them.
with open("../"
          "trials_factor_2026-07/E5_skeptic_attacks.json") as _f:
    _a8 = json.load(_f)["attack8_ladder_budget"]
p_false_alpha_per_ladder = float(_a8["p_false_alpha_per_ladder"])   # was hard-coded 6.6e-7
n_ladders = int(_a8["conservative_ladder_count"])                   # was hard-coded 10_800
exp_false_alpha = p_false_alpha_per_ladder * n_ladders
ladders_needed = 1.0 / p_false_alpha_per_ladder
out['alpha_ladder'] = dict(expected_false_alphas=exp_false_alpha,
                           ladders_needed=ladders_needed,
                           ladders_present=n_ladders)

# ------------------------------------------------ 3. EFFECTIVE HITS (SK2 recount)
# SK2 floor = 3 effective independent hits, menu-charged p-values:
#   sin^2 thetaW : rational-menu 1/12 (conservative) .. 1/56 (moderate)
#   H0/Lambda/a0 block : AU grammar 3/135 (cons) .. x SH0ES window 0.074 -> 1.66e-3 (mod)
#   Omega_chi h^2 : E4-hostile 0.136 (both tiers; worst of menu & window charges)
hits_cons = {'sin2thetaW': 1/12, 'H0_Lambda_a0_block': 3/135, 'Omega_chi': 0.136}
hits_mod  = {'sin2thetaW': 1/56, 'H0_Lambda_a0_block': (3/135)*0.074, 'Omega_chi': 0.136}
p_flag_cons = math.prod(hits_cons.values())
p_flag_mod  = math.prod(hits_mod.values())
out['flagship_no_selection'] = dict(
    conservative=dict(p=p_flag_cons, Z=Z(p_flag_cons), hits=hits_cons),
    moderate=dict(p=p_flag_mod, Z=Z(p_flag_mod), hits=hits_mod))

# ------------------------------------- 4. FAIREST NULL: order-statistics selection
# M booked comparisons in corpus (~12 conservative booking .. 20 max booking);
# skeptic may pick the k=3 best. Null: M iid uniforms, stat = product of 3 smallest.
rng = np.random.default_rng(20260702)
NSIM = 4_000_000
def selection_p(obs_product, M, k=3, nsim=NSIM):
    u = rng.random((nsim, M))
    u.partition(k-1, axis=1)
    stat = np.prod(u[:, :k], axis=1)
    return float(np.mean(stat <= obs_product))

sel = {}
for tag, obs in [('conservative', p_flag_cons), ('moderate', p_flag_mod)]:
    for M in (12, 20):
        p = selection_p(obs, M)
        sel[f'{tag}_M{M}'] = dict(p=p, Z=Z(p) if p < 0.5 else 0.0)
out['selection_null'] = sel
worst_p = max(v['p'] for v in sel.values())
headline_sel_mod_M20 = sel['moderate_M20']['p']
out['worst_case'] = dict(p=worst_p, note='conservative windows + M=20 full selection charge')

# ------------------------------------------------ 5. SENSITIVITY: halved hits
# (a) drop weakest hit (Omega_chi) -> k=2 ; (b) double every window (halve each hit strength)
hits2_cons = {k: v for k, v in hits_cons.items() if k != 'Omega_chi'}
hits2_mod  = {k: v for k, v in hits_mod.items()  if k != 'Omega_chi'}
p2_cons, p2_mod = math.prod(hits2_cons.values()), math.prod(hits2_mod.values())
def selection_p_k(obs, M, k):
    u = rng.random((2_000_000, M)); u.partition(k-1, axis=1)
    return float(np.mean(np.prod(u[:, :k], axis=1) <= obs))
pdbl_cons = math.prod(min(2*v, 1.0) for v in hits_cons.values())
pdbl_mod  = math.prod(min(2*v, 1.0) for v in hits_mod.values())
out['sensitivity'] = dict(
    drop_weakest=dict(cons=dict(p=p2_cons, Z=Z(p2_cons)),
                      mod=dict(p=p2_mod, Z=Z(p2_mod)),
                      sel_M12_mod=selection_p_k(p2_mod, 12, 2)),
    doubled_windows=dict(cons=dict(p=pdbl_cons, Z=Z(pdbl_cons)),
                         mod=dict(p=pdbl_mod, Z=Z(pdbl_mod))))

# ------------------------------------------------ 6. LADDER OF NULLS (final book)
out['final_ladder'] = {
    'NULL-A_appCE_magnitude (corpus own, floor-5 hits)': dict(p=7.95e-9, Z=Z(7.95e-9), status='SUPERSEDED as headline (does not charge selection or menus)'),
    'NULL-B_uniform_address_E4 (pre-SK1 space)': dict(p=8.3e-5, Z=Z(8.3e-5), status='space now x43,200 larger but hits alpha-dead (sec 2): p unchanged to 1st order, keep as secondary'),
    'NULL-C_flagship_conditional (3 hits, menu-charged, NO selection charge)': dict(p_cons=p_flag_cons, Z_cons=Z(p_flag_cons), p_mod=p_flag_mod, Z_mod=Z(p_flag_mod), status='HEADLINE, conditional on pre-registered-flagship framing'),
    'NULL-D_full_selection_charge (fairest hostile)': dict(p_mod_M12=sel['moderate_M12']['p'], p_mod_M20=sel['moderate_M20']['p'], p_cons_M12=sel['conservative_M12']['p'], p_cons_M20=sel['conservative_M20']['p'], status='WORST CASE: not significant; theorem must be stated conditionally'),
}

with open('E6_synthesis.json', 'w') as f:
    json.dump(out, f, indent=2, default=float)

print(json.dumps(out, indent=2, default=float))
