#!/usr/bin/env python3
"""
E5: SKEPTIC-COMPLETENESS attack on the E1/E2 enumeration. HONESTY-GUARD MAXIMAL.
Every number computed. Corpus citations verified 2026-07-02 (READ-ONLY):
  AB = appendix_AB_uniqueness.tex (V1-V9 L12-33; lem:uniq-split L46-63; lem:uniq-Mc L67-96
       Fano table {CP2:3, CP1xCP1:4, dP_k:3+k}; lem:uniq-Mg L98-105 SO(3) exclusion "by the
       requirement (V4) that M_g is a Lie group rather than a quotient" -- but V4 L21 verbatim
       ALLOWS "a compact Lie group or group quotient" = INTERNAL CONTRADICTION)
  O  = appendix_O_alpha57.tex (lem:O_KK L128-152: 57=60-3 with confession "the earlier phrasing
       ind(D_K)=3 was therefore incorrect as written"; L11+L236 cutoff-free claim, plateau cutoff L185)
  F  = appendix_F.tex (L121 integrality table row "5/3 ... x-mark": GUT normalization FAILS integrality)
  AO = appendix_AO_ckm_update.tex (L141 "In the Wolfenstein convention"; L151 barred coords
       "standard global-fit conventions"; L160 "in the standard parametrization")
  E2 = E2_enumeration.json (totals: core cons 185472, full cons 47480832; hit-capability lemma)
  E4 = E4_results.json (NULL3 worst-case p=8.465e-4, paranoid rungs already computed)
"""
from math import comb, pi, sqrt
import json
from statistics import NormalDist

N = NormalDist()
out = {}

# ---------------- shared machinery: the CP2 alpha ladder (from E1, re-verified) ----------------
alpha_inv = lambda k: (pi ** 1.5 / 24) * 10 * k * (k + 3) / (k + 4) * (1 + 7 / (80 * ((k + 4) ** 2 - 1)))
step = alpha_inv(61) - alpha_inv(60)
ppm_match = abs(alpha_inv(60) - 137.035999084) / 137.035999084 * 1e6   # DFD's actual match quality

# =====================================================================================
# ATTACK 1 -- M_c MULTIPLICITY: thm:uniqueness conditions on chi=3 (V5) = observed N_gen.
# The E1/E2 space VARIES N_gen 1..9, so V5 becomes chi=N_gen and lem:uniq-Mc no longer
# yields a unique surface. Fano classification (cited in AB, Hirzebruch): CP2 (chi=3),
# CP1xCP1 (4), dP_k (3+k), k=1..8. Countable, FINITE (classification theorem) => COUNTED.
fano = {"CP2": 3, "CP1xCP1": 4, **{f"dP{k}": 3 + k for k in range(1, 9)}}
mult = {ng: sum(1 for s, c in fano.items() if c == ng) for ng in range(1, 10)}
# N_gen=1,2: NO Fano surface (chi_min=3); non-Fano chi=1,2 exist but violate the
# Ricci-positivity the gauge-emergence stiffness requires (AB lem:uniq-Mc closing argument)
# => those addresses are manifold-empty; honesty-guard KEEPS them (removing shrinks space).
out["attack1_Mc_multiplicity"] = {
    "fano_chi": fano, "multiplicity_by_Ngen": mult,
    "verdict": "COUNTED-ENLARGEMENT. Surface coordinate: baseline 1 (N_gen=3 => CP2 unique, "
               "50 fake projective planes killed by Ricci-positivity, conditional on the "
               "gauge-emergence mechanism); conservative 10 (full Fano menu as a free coordinate).",
    "multiplier_cons": 10,
    "residual_hole": "Picard rank of dP_k is k+1: line bundles at fixed index form a Lorentzian "
                     "lattice level set = COUNTABLY INFINITE rays per surface. NOT uncountable. "
                     "Collapses only under R1 IF observables depend on the bundle through rank "
                     "k_max alone -- true for the CP2 chain, UNPROVEN for dP_k. Truncation = same "
                     "policy class as the N_gen cap. Charged via the ladder-count budget (Attack 8)."}

# =====================================================================================
# ATTACK 2 -- M_g QUOTIENTS: V4 (L21) verbatim allows "group quotient"; lem:uniq-Mg excludes
# SO(3) "by the requirement (V4) that M_g is a Lie group rather than a quotient". Internal
# contradiction => quotient exclusion is FIAT + physics gloss ("discrete hair"), no theorem.
# Lens family L(p,1)=S^3/Z_p: pi_3=Z for all p, homogeneous, countably infinite.
# Truncation: SU(2) CS structure at level 60 needs 60/p integral => p | 60.
divisors60 = [p for p in range(1, 61) if 60 % p == 0]
out["attack2_Mg_lens"] = {
    "V4_contradiction": "V4 allows quotients; lemma denies citing V4 -- verbatim clash (AB L21 vs L104)",
    "lens_truncation_p_divides_60": divisors60, "count": len(divisors60),
    "verdict": "COUNTED-ENLARGEMENT x12 on the M_g coordinate (baseline 1, kept: discrete-hair "
               "argument is corpus-physics, adopted as an axiom-bit not a theorem). Countable tail "
               "p not dividing 60 is level-integrality dead (CS quantization broken => no alpha "
               "selector => hit-dead).",
    "multiplier_cons": len(divisors60),
    "hit_side": "lens addresses change Q_CS (Omega_chi engine) => charges Omega_chi trials in E4's "
                "worst-case null; but most p break the level-60 alpha selector first (selector-filter)."}

# =====================================================================================
# ATTACK 3 -- dim X = 7 (V2): justified by MINIMALITY ('the minimal internal dimension that
# admits...') + consistency with alpha^57 -- the latter is CIRCULAR (57 is derived ON X).
# Minimality = selection principle = same epistemic class the ledger assigns to minimal
# padding ('SM-content choices, not index outputs'). Admissible higher dims under V4+V5+V7:
# M_c Kahler even-dim x M_g with pi_3=Z (dim>=3, simply-connected 3d => S^3; 5d groups with
# pi_3=Z all fail simple-connectedness like SO(3)): dims = 4+3=7, 6+3=9, 8+3=11, ...
out["attack3_dimX"] = {
    "circularity": "V2's alpha^57-consistency clause uses the invariant derived on X = assumes what it proves",
    "admissible_dims_cons": [7, 9, 11],
    "verdict": "COUNTED-ENLARGEMENT x3 conservative (cap at 11 = policy, same class as N_gen cap; "
               "dim 9 alone opens ~105 Fano 3-fold families -- folded into the ladder budget, Attack 8).",
    "multiplier_cons": 3}

# =====================================================================================
# ATTACK 4 -- alpha-FORMULA GRAMMAR: prefactor pi^1.5/24, plateau cutoff, 2-loop-like
# correction 1+7/(80(d^2-1)). Corpus: O L11/L236 claims finite product, "no cutoff
# dependence"; memory alpha_cutoff_robustness = geometry-only cutoffs AGREE (degenerate).
# TrY^2 normalization: GUT 5/3 row FAILS integrality (F table L121, x-mark) => normalization
# is EXCLUDED not chosen => NO hit-side charge on sin^2thW; keep x2 address bit conservatively.
out["attack4_formula_grammar"] = {
    "cutoff_menu": "x1 baseline (cutoff-free theorem O L236 + robustness memory); x3 conservative "
                   "(plateau/sharp/heat-kernel readings kept as addresses despite proven degeneracy)",
    "TrY2_norm_bit": "x2 address bit; hit-dead (5/3 integrality-excluded, F L121)",
    "multiplier_cons": 3 * 2}

# =====================================================================================
# ATTACK 5 -- WOLFENSTEIN BASIS: AO L141/151/160 -- the integer grammar (31,108,43/2,49)
# lives in a NAMED convention ("Wolfenstein", "standard global-fit conventions").
# Basis menu: {Wolfenstein barred, PDG standard angles, Jarlskog/moduli} = 3.
# Physical CKM is basis-invariant but WHICH numbers look integer-clean is basis-DEPENDENT
# => genuine grammar dimension the E1 CKM count (x8) missed.
out["attack5_wolfenstein"] = {"basis_menu": ["Wolfenstein-barred", "PDG-angles", "Jarlskog-moduli"],
                              "multiplier_cons": 3,
                              "verdict": "COUNTED-ENLARGEMENT: CKM dim 8 -> 24 conservative."}

# =====================================================================================
# ATTACK 6 -- 57 = k_max - N_gen SUBTRACTION RULE: O lem:O_KK ADMITS the earlier index
# phrasing was 'incorrect as written'; the repaired statement embeds the 3-dim generation
# sector INSIDE the 60-dim microsector (so subtract) rather than adjoining it (so don't).
# The embedding is an identification, not an index theorem => rule menu {57, 60} minimum.
out["attack6_subtraction_rule"] = {
    "menu": ["k_max - N_gen (embedded, corpus)", "k_max (adjoined)"],
    "multiplier_cons": 2,
    "hit_side": "charges the H0/Lambda 57-exponent hit x2 in worst-case pricing"}

# =====================================================================================
# ATTACK 7 -- AU PREFACTOR LIST COMPLETENESS: 9 declared; natural closure of the grammar
# {a/(b*pi^m): a in 1..4, b in {1,2,4,8}, m in {-1,0,1}} distinct values:
from fractions import Fraction
vals = set()
for a in (1, 2, 3, 4):
    for b in (1, 2, 4, 8):
        for m in (-1, 0, 1):
            vals.add((Fraction(a, b), m))
out["attack7_prefactor_completion"] = {
    "declared": 9, "natural_closure_count": len(vals),
    "multiplier_cons": len(vals) / 9,
    "note": "Enlarging the scanned menu RAISES the look-elsewhere trials on the rho_Lambda hit "
            "by x{:.1f}; harmless at address level (counted), charged hit-side.".format(len(vals) / 9)}

# =====================================================================================
# ATTACK 8 -- HIT-CAPABILITY LEMMA SCOPE (assumes what it proves): E2's lemma covers ONE
# ladder (the CP2 formula, vary k). Every enlargement above that changes the SURFACE,
# QUOTIENT, DIM, or FORMULA creates a NEW monotone ladder with its own shot at alpha.
# Per-ladder false-positive probability (a match as good as DFD's 0.0056 ppm):
p_ladder = 2 * 137.036 * (ppm_match * 1e-6) / step
n_ladders_cons = 10 * 10 * 12 * 3 * 3   # surfaces x truncated Picard rays x lens x dims x formula
exp_false = p_ladder * n_ladders_cons
n_needed = 1 / p_ladder
out["attack8_ladder_budget"] = {
    "p_false_alpha_per_ladder": p_ladder, "ppm_match": ppm_match, "step_alpha_units": step,
    "conservative_ladder_count": n_ladders_cons,
    "expected_false_subppm_alphas": exp_false,
    "ladders_needed_to_fake_alpha": n_needed,
    "verdict": "alpha-selector SURVIVES the enlarged space: expected false matches at least as "
               "good as the observed 0.0056 ppm = {:.1e} << 1; you would need ~{:.0f} independent "
               "ladders -- x{:.0f} the full 10,800-ladder enlarged menu (the earlier '~4000x' figure "
               "was an error: x4,180 holds only vs the 360-ladder sub-menu; re-verification C8) -- to make "
               "the alpha coincidence unremarkable. Unbounded Picard/dim tails need a truncation "
               "POLICY (honest hole, same class as the N_gen cap), not uncountable."
               .format(exp_false, n_needed, n_needed / n_ladders_cons)}

# =====================================================================================
# ATTACK 9 -- CONTINUOUS (UNCOUNTABLE) DIMENSION HUNT: metric moduli.
# alpha ladder k(k+3)/(k+4) is metric-SCALE-free; shape moduli would be a continuous dial.
# Rigidity: CP2 Kahler-Einstein metric = Fubini-Study, UNIQUE (Fano KE uniqueness,
# Bando-Mabuchi); 3d Einstein = constant curvature => round S^3 unique. Deforming the
# metric off Einstein breaks the isometry group = breaks V6's gauge partition.
# => NO uncountable dimension PROVIDED the Einstein/isometry-maximal condition is part of
# the core mechanism (it is: gauge group = isometry group). Conditional, named.
out["attack9_metric_moduli"] = {
    "verdict": "NO uncountable dimension found. Metric moduli killed by Bando-Mabuchi KE "
               "uniqueness on CP2 + 3d Einstein rigidity on S^3, CONDITIONAL on the "
               "gauge-from-isometry mechanism (corpus core, same conditioning E2 already carries "
               "for the dim<=28 bound). chi-primordial continuous reading already carried by E2."}

# =====================================================================================
# CORRECTED TOTALS
E2core, E2full = 185472, 47480832
mults = {"Mc_surface": 10, "Mg_lens": 12, "dimX": 3, "formula+TrY2": 6,
         "Wolfenstein": 3, "subtraction_rule": 2, "prefactor_completion": len(vals) / 9}
M = 1
for v in mults.values():
    M *= v
out["corrected_totals"] = {
    "multipliers": mults, "total_multiplier": M,
    "core_conservative_E5": E2core * M, "full_conservative_E5": E2full * M,
    "core_str": "{:.2e}".format(E2core * M), "full_str": "{:.2e}".format(E2full * M)}

# =====================================================================================
# SIGNIFICANCE IMPACT (worst-case NULL3 re-pricing; E4 per-hit p's, charged per attack)
def Z(p): return N.inv_cdf(1 - p) if p < 0.5 else 0.0
s2w, H0L, Ochi = 0.0266, 0.234, 0.136
# (a) FULL-PARANOIA: charge lens x12 to Omega_chi (no selector-filter), x2 subtraction and
#     x2.67 prefactor-completion to H0/Lambda; TrY2 NOT charged (integrality-excluded).
Ochi_a = min(1.0, Ochi * 12); H0L_a = min(1.0, H0L * 2 * (len(vals) / 9))
surv_a = [p for p in (s2w, H0L_a if H0L_a < 1 else None, Ochi_a if Ochi_a < 1 else None) if p]
p_a = 1.0
for q in surv_a: p_a *= q
# (b) SELECTOR-FILTERED: lens p in {1,2} keep level-60 readable => x2 on Omega_chi;
#     subtraction x2 on H0/Lambda; prefactor completion charged x2.67 on H0/Lambda too.
Ochi_b = min(1.0, Ochi * 2); H0L_b = min(1.0, H0L * 2 * (len(vals) / 9))
p_b = s2w * (H0L_b if H0L_b < 1 else 1) * Ochi_b
out["significance_impact"] = {
    "E4_original_NULL3": {"p": 8.465e-4, "Z": 3.14},
    "full_paranoia": {"surviving": ["s2w"] + (["H0L"] if H0L_a < 1 else []) + (["Ochi"] if Ochi_a < 1 else []),
                      "p": p_a, "Z": Z(p_a)},
    "selector_filtered": {"p": p_b, "Z": Z(p_b)},
    "note": "Full-paranoia floor collapses to E4's own pre-computed paranoid_s2w_only rung; "
            "the enlargements land INSIDE E4's already-published sensitivity band [1.9, 3.1]sigma."}

print(json.dumps(out, indent=1, default=str))
json.dump(out, open("E5_skeptic_attacks.json", "w"), indent=1, default=str)
