#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
================================================================================
LEECH MINIMAL SHELL: UNIVERSAL INTEGER BRIDGE & SELF-DUAL STABILITY CONE AUDIT
File: leech_universal_bridge.py
Archive: srfp311t1 // Tier I Exact Rational (QQ) & Integer (ZZ) Certificate
================================================================================

End-to-end, zero-shortcut verification of:
  1. Extended Binary Golay Code [24, 12, 8] & 196,560 minimal Leech vectors.
  2. First-principles construction of the 11 stratum Hessian matrices K_s, L_s
     over QQ on the 12-dimensional Co_2-intertwiner space M = Hom_K(T_u S^23, T).
  3. Pairwise commutativity [K_s, K_t] = [K_s, L_t] = [L_s, L_t] = 0 over QQ
     and simultaneous diagonalization by primitive integer eigenvectors V in M_12(ZZ).
  4. Peter-Weyl Impulse Identity: v_i^T G v_i = kappa_i * v_{i,0} with
     kappa_i = (4,520,880 / d_i) * v_{i,0} and sum_{i=0}^{11} (1/kappa_i) v_i = e_0.
  5. Extraction of the Universal Integer Bridge Matrices Omega_K in M_{12x6}(ZZ)
     and Omega_L in M_{12x5}(ZZ).
  6. Invertibility of the 11x11 active bridge matrix Omega_active and exact
     prime factorization: det(Omega_active) = 2^50 * 3^22 * 5^9 * 7^4 * 13^3 * 23.
  7. Peter-Weyl Self-Duality of the Simplicial Stability Cone:
     Omega_active * j(v_i) = kappa_i * e_i (i=1..11) and Goldstone Casimir
     identity Omega_active * (-j(v_0)) = 524,160 * (1,...,1)^T.
  8. All Six Universal Conservation and Finite-Difference Laws (Laws I-VI).
  9. Upper-Triangular Spherical 11-Design Polynomial Ladder T_poly and the
     11 exact monic mode-isolating polynomials P_1(s), ..., P_11(s) in QQ[s].

Dependencies: numpy, sympy
Run:          python3 leech_universal_bridge.py
================================================================================
"""

import time
from itertools import combinations
import numpy as np
import sympy as sp


def run_universal_bridge_audit():
    t_start = time.time()

    print("=" * 80)
    print("LEECH LATTICE UNIVERSAL INTEGER BRIDGE & SELF-DUAL CONE CERTIFICATE")
    print("=" * 80)

    # ==========================================================================
    # 0. FUNDAMENTAL CONSTANTS & MULTIPLICITIES
    # ==========================================================================
    D = 24
    R2 = 32
    N = 196560
    TANGENT_DIM = 23
    FULL_DIM = N * TANGENT_DIM  # 4,520,880

    allowed_shells = [32, 16, 8, 0, -8, -16, -32]
    int_shells = [16, 8, 0, -8, -16, -32]
    curved_shells = [16, 8, 0, -8, -16]

    expected_shell_sizes = {
        32: 1, 16: 4600, 8: 47104, 0: 93150, -8: 47104, -16: 4600, -32: 1
    }
    expected_multiplicities = [
        276, 4576, 44275, 315744, 1821600, 1841840,
        376740, 95680, 17250, 2576, 299, 24
    ]
    assert sum(expected_multiplicities) == FULL_DIM

    # ==========================================================================
    # 1. EXTENDED BINARY GOLAY CODE [24, 12, 8] & 196,560 MINIMAL VECTORS
    # ==========================================================================
    print("\n[1] GENERATING GOLAY CODE [24,12,8] & 196,560 MINIMAL LEECH VECTORS")
    print("-" * 80)

    B12 = np.array([
        [1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 0, 1],
        [1, 0, 1, 1, 1, 0, 0, 0, 1, 0, 1, 1],
        [0, 1, 1, 1, 0, 0, 0, 1, 0, 1, 1, 1],
        [1, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1],
        [1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1],
        [1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 1],
        [0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1],
        [0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1],
        [0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1],
        [1, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1],
        [0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1],
        [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0]
    ], dtype=np.int64)
    G_golay = np.hstack([np.eye(12, dtype=np.int64), B12])

    inputs = np.array([[(m >> k) & 1 for k in range(12)] for m in range(4096)], dtype=np.int64)
    codewords = (inputs @ G_golay) % 2
    weights = np.sum(codewords, axis=1)
    octads = codewords[weights == 8]
    assert len(codewords) == 4096 and len(octads) == 759

    # Family A: (±4, ±4, 0^22) -> 1,104 vectors
    X_A = np.zeros((1104, 24), dtype=np.int64)
    row_idx = 0
    for i, j in combinations(range(24), 2):
        for s1 in (4, -4):
            for s2 in (4, -4):
                X_A[row_idx, i] = s1
                X_A[row_idx, j] = s2
                row_idx += 1

    # Family B: (±2^8, 0^16) on octads with even sign parity -> 97,152 vectors
    even_masks = [m for m in range(256) if bin(m).count('1') % 2 == 0]
    signs_pattern = np.array(
        [[-2 if ((m >> k) & 1) else 2 for k in range(8)] for m in even_masks],
        dtype=np.int64
    )
    X_B = np.zeros((759 * 128, 24), dtype=np.int64)
    for idx, octad in enumerate(octads):
        pos = np.where(octad == 1)[0]
        X_B[idx * 128:(idx + 1) * 128, pos] = signs_pattern

    # Family C: (±3, ±1^23) -> 98,304 vectors
    cw_array = np.where(codewords == 0, 1, -1).astype(np.int64)
    X_C = np.zeros((4096 * 24, 24), dtype=np.int64)
    for m in range(24):
        v_block = cw_array.copy()
        v_block[:, m] *= -3
        X_C[m * 4096:(m + 1) * 4096] = v_block

    X_np = np.vstack([X_A, X_B, X_C])
    assert X_np.shape == (N, D)
    assert np.all(np.sum(X_np * X_np, axis=1) == R2)

    u_np = X_np[0].copy()
    inner_products = X_np @ u_np
    shell_indices = {s: np.where(inner_products == s)[0] for s in allowed_shells}
    shell_sizes = {s: len(shell_indices[s]) for s in allowed_shells}
    assert shell_sizes == expected_shell_sizes

    shell_data_np = {s: X_np[shell_indices[s]] for s in allowed_shells}
    rep_np = {s: shell_data_np[s][0] for s in allowed_shells}
    print("[OK] 196,560 minimal vectors and 7 shell strata certified.")

    # ==========================================================================
    # 2. EXACT TANGENT BASIS, 12 INTERTWINER FIELDS & EVALUATION MATRIX
    # ==========================================================================
    print("\n[2] CONSTRUCTING 12 Co_2-INTERTWINER FIELDS & EVALUATION MATRIX")
    print("-" * 80)

    T_selected = []
    for j in range(24):
        e = np.zeros(24, dtype=np.int64)
        e[j] = 1
        t_vec = 32 * e - int(u_np[j]) * u_np
        if np.any(t_vec != 0):
            trial = np.array(T_selected + [t_vec])
            if np.linalg.matrix_rank(trial) > len(T_selected):
                T_selected.append(t_vec)
            if len(T_selected) == 23:
                break
    T_np = np.array(T_selected, dtype=np.int64)
    assert T_np.shape == (23, 24)

    field_specs = [
        (32,  "W1"), (16,  "W1"), (16,  "W2"), (8,   "W1"),
        (8,   "W2"), (0,   "W1"), (0,   "W2"), (-8,  "W1"),
        (-8,  "W2"), (-16, "W1"), (-16, "W2"), (-32, "W1")
    ]

    def eval_field_on_set_32(b, z_vec, Y_mat):
        shell, kind = field_specs[b]
        zv = Y_mat @ z_vec
        if kind == "W1":
            return 32 * z_vec[None, :] - zv[:, None] * Y_mat
        else:
            return zv[:, None] * (32 * u_np[None, :] - shell * Y_mat)

    def field_val_exact_sp(b, z_vec, v_vec):
        shell, kind = field_specs[b]
        if int(np.dot(u_np, v_vec)) != shell:
            return [sp.Rational(0)] * 24
        zv = int(np.dot(z_vec, v_vec))
        if kind == "W1":
            return [sp.Rational(int(z_vec[i])) - sp.Rational(zv * int(v_vec[i]), 32) for i in range(24)]
        else:
            return [sp.Rational(zv) * (sp.Rational(int(u_np[i])) - sp.Rational(shell * int(v_vec[i]), 32)) for i in range(24)]

    eval_probes = []
    eval_rows = []
    for s in allowed_shells:
        v = rep_np[s]
        if s == 0:
            eval_probes.append((v, T_np[1], 2))
            eval_rows.append([field_val_exact_sp(b, T_np[1], v)[2] for b in range(12)])
            eval_probes.append((v, T_np[0], 0))
            eval_rows.append([field_val_exact_sp(b, T_np[0], v)[0] for b in range(12)])
        elif s in (32, -32):
            eval_probes.append((v, T_np[0], 0))
            eval_rows.append([field_val_exact_sp(b, T_np[0], v)[0] for b in range(12)])
        else:
            idx_w1 = [i for i, spec in enumerate(field_specs) if spec == (s, "W1")][0]
            idx_w2 = [i for i, spec in enumerate(field_specs) if spec == (s, "W2")][0]
            w1 = field_val_exact_sp(idx_w1, T_np[0], v)
            w2 = field_val_exact_sp(idx_w2, T_np[0], v)
            for q1 in range(24):
                for q2 in range(q1 + 1, 24):
                    if w1[q1] * w2[q2] - w1[q2] * w2[q1] != 0:
                        eval_probes.append((v, T_np[0], q1))
                        eval_rows.append([field_val_exact_sp(b, T_np[0], v)[q1] for b in range(12)])
                        eval_probes.append((v, T_np[0], q2))
                        eval_rows.append([field_val_exact_sp(b, T_np[0], v)[q2] for b in range(12)])
                        break
                else:
                    continue
                break

    Eval_sp = sp.Matrix(eval_rows)
    assert Eval_sp.rank() == 12
    Eval_inv = Eval_sp.inv()
    print("[OK] 12x12 Evaluation matrix inverted over QQ (rank = 12).")

    # ==========================================================================
    # 3. FIRST-PRINCIPLES STRATUM HESSIAN MATRICES K_s AND L_s OVER QQ
    # ==========================================================================
    print("\n[3] BUILDING FIRST-PRINCIPLES STRATUM MATRICES K_s AND L_s OVER QQ")
    print("-" * 80)

    W_cache = {}
    for b in range(12):
        s_b, _ = field_specs[b]
        Y_b = shell_data_np[s_b]
        W_cache[(b, 0)] = eval_field_on_set_32(b, T_np[0], Y_b)
        W_cache[(b, 1)] = eval_field_on_set_32(b, T_np[1], Y_b)

    K_mats = {}
    L_mats = {}

    for s_int in int_shells:
        probe_Fp = sp.zeros(12, 12)
        probe_Fpp = sp.zeros(12, 12)
        for row_i, (x_vec, z_vec, q_coord) in enumerate(eval_probes):
            z_idx = 0 if np.array_equal(z_vec, T_np[0]) else 1
            for b in range(12):
                s_b, _ = field_specs[b]
                Y_b = shell_data_np[s_b]
                mask = (Y_b @ x_vec == s_int)
                if not np.any(mask):
                    continue
                Y_sub = Y_b[mask]
                W_sub = W_cache[(b, z_idx)][mask]

                sum_W = np.sum(W_sub, axis=0)
                w_dot_x = int(np.dot(sum_W, x_vec))
                pi_x_W_q = sp.Rational(32 * int(sum_W[q_coord]) - w_dot_x * int(x_vec[q_coord]), 1024)
                probe_Fp[row_i, b] = -pi_x_W_q

                x_dot_W = W_sub @ x_vec
                sum_xWy = x_dot_W @ Y_sub
                sum_xW_scalar = int(np.sum(x_dot_W))
                pi_x_Y_q = sp.Rational(
                    32 * int(sum_xWy[q_coord]) - s_int * sum_xW_scalar * int(x_vec[q_coord]), 1024
                )
                probe_Fpp[row_i, b] = pi_x_Y_q

        cnt = shell_sizes[s_int]
        diag_Fp = sp.Rational(cnt * s_int, 32)
        diag_Fpp = sp.Rational(cnt * (1024 - s_int**2), 32 * 23)

        K_mats[s_int] = Eval_inv * probe_Fp + diag_Fp * sp.eye(12)
        L_mats[s_int] = Eval_inv * probe_Fpp + diag_Fpp * sp.eye(12)

    assert L_mats[-32] == sp.zeros(12, 12)

    all_stratum_mats = [K_mats[s] for s in int_shells] + [L_mats[s] for s in curved_shells]
    for i in range(len(all_stratum_mats)):
        for j in range(i + 1, len(all_stratum_mats)):
            assert all_stratum_mats[i] * all_stratum_mats[j] == all_stratum_mats[j] * all_stratum_mats[i]

    print("[OK] All 11 stratum matrices {K_s, L_s} constructed and verified to commute pairwise over QQ.")

    # ==========================================================================
    # 4. SIMULTANEOUS EIGENVECTORS V & PETER-WEYL IMPULSE IDENTITY
    # ==========================================================================
    print("\n[4] EXTRACTING SIMULTANEOUS INTEGER EIGENVECTORS V & PETER-WEYL CONSTANTS")
    print("-" * 80)

    expected_roots = [
        sp.Rational(0),
        sp.Rational(73073, 58982400),
        sp.Rational(219791, 92160000),
        sp.Rational(558817, 163840000),
        sp.Rational(24731, 5760000),
        sp.Rational(1479317, 294912000),
        sp.Rational(199381, 18432000),
        sp.Rational(40598593, 1474560000),
        sp.Rational(872241, 10240000),
        sp.Rational(432845153, 1474560000),
        sp.Rational(797071, 737280),
        sp.Rational(24913889, 6553600)
    ]

    A_riesz = sp.zeros(12, 12)
    for s_int in int_shells:
        U = 64 - 2 * s_int
        A_riesz += sp.Rational(-4, U**3) * K_mats[s_int] + sp.Rational(24, U**4) * L_mats[s_int]

    eigvecs = []
    for r in expected_roots:
        ns = (A_riesz - r * sp.eye(12)).nullspace()
        assert len(ns) == 1
        v = ns[0]
        lcm_den = sp.ilcm(*[x.q for x in v])
        v_int = v * lcm_den
        gcd_num = sp.igcd(*[abs(x.p) for x in v_int if x != 0])
        v_prim = v_int / gcd_num
        if v_prim[0] < 0:
            v_prim = -v_prim
        eigvecs.append(v_prim)

    V_mat = sp.Matrix.hstack(*eigvecs)
    V_inv = V_mat.inv()

    # Exact rational Gram matrix G from spherical 2-design moments
    G_exact = sp.zeros(12, 12)
    for a in range(12):
        s_a, k_a = field_specs[a]
        Ns = shell_sizes[s_a]
        cs = sp.Rational(Ns * (32 - sp.Rational(s_a**2, 32)), 23)
        for b in range(12):
            s_b, k_b = field_specs[b]
            if s_a != s_b:
                continue
            if k_a == "W1" and k_b == "W1":
                G_exact[a, b] = Ns - cs / 32
            elif k_a == "W2" and k_b == "W2":
                G_exact[a, b] = cs * (32 - sp.Rational(s_a**2, 32))
            else:
                G_exact[a, b] = -sp.Rational(s_a, 32) * cs

    G_diag = V_mat.T * G_exact * V_mat
    assert G_diag.is_diagonal()

    kappas = []
    for i in range(12):
        v_i0 = V_mat[0, i]
        kap = sp.Rational(FULL_DIM, expected_multiplicities[i]) * v_i0
        assert G_diag[i, i] == kap * v_i0
        kappas.append(int(kap))

    e0_recon = sum((V_mat[:, i] / sp.Rational(kappas[i]) for i in range(12)), sp.zeros(12, 1))
    assert list(e0_recon) == [1] + [0] * 11
    print("[OK] Peter-Weyl Impulse Identity certified: v_i^T G v_i = kappa_i * v_{i,0} and sum(v_i / kappa_i) = e_0.")

    # ==========================================================================
    # 5. UNIVERSAL INTEGER BRIDGE MATRICES Omega_K AND Omega_L
    # ==========================================================================
    print("\n[5] EXTRACTING UNIVERSAL INTEGER BRIDGE MATRICES Omega_K & Omega_L")
    print("-" * 80)

    Omega_K = sp.zeros(12, 6)
    Omega_L = sp.zeros(12, 5)

    for col_j, s_int in enumerate(int_shells):
        DK = V_inv * K_mats[s_int] * V_mat
        assert DK.is_diagonal()
        for mode_i in range(12):
            val = DK[mode_i, mode_i]
            assert val.q == 1  # Strictly integer!
            Omega_K[mode_i, col_j] = val

    for col_j, s_int in enumerate(curved_shells):
        DL = V_inv * L_mats[s_int] * V_mat
        assert DL.is_diagonal()
        for mode_i in range(12):
            val = DL[mode_i, mode_i]
            assert val.q == 1  # Strictly integer!
            Omega_L[mode_i, col_j] = val

    print("[OK] All entries of Omega_K (12x6) and Omega_L (12x5) certified to lie in ZZ.")

    # ==========================================================================
    # 6. 11x11 BRIDGE BIJECTION, PRIME DETERMINANT & SELF-DUALITY
    # ==========================================================================
    print("\n[6] CERTIFYING 11x11 BRIDGE ISOMORPHISM, DETERMINANT & SELF-DUALITY")
    print("-" * 80)

    Omega_active = sp.Matrix.hstack(Omega_K[1:, :], Omega_L[1:, :])
    assert Omega_active.shape == (11, 11) and Omega_active.rank() == 11

    det_val = Omega_active.det()
    expected_det_factors = {2: 50, 3: 22, 5: 9, 7: 4, 13: 3, 23: 1}
    assert sp.factorint(det_val) == expected_det_factors
    print(f"[OK] det(Omega_active) = {det_val}")
    print(f"[OK] Prime factorization certified: {expected_det_factors}")

    w1_indices = [1, 3, 5, 7, 9, 11]
    w2_indices = [2, 4, 6, 8, 10]

    for mode_i in range(1, 12):
        v = V_mat[:, mode_i]
        jet_vi = sp.Matrix([-v[idx] for idx in w1_indices] + [v[idx] for idx in w2_indices])
        spec = Omega_active * jet_vi
        expected_spec = sp.zeros(11, 1)
        expected_spec[mode_i - 1] = kappas[mode_i]
        assert spec == expected_spec

    v0 = V_mat[:, 0]
    jet_v0 = sp.Matrix([-v0[idx] for idx in w1_indices] + [v0[idx] for idx in w2_indices])
    assert list(Omega_active * (-jet_v0)) == [524160] * 11
    print("[OK] Self-Duality Omega_active * j(v_i) = kappa_i * e_i and Casimir constant 524,160 certified.")

    # ==========================================================================
    # 7. SIX UNIVERSAL CONSERVATION & FINITE-DIFFERENCE LAWS (THEOREM 5.1)
    # ==========================================================================
    print("\n[7] CERTIFYING THE SIX UNIVERSAL CONSERVATION & DIFFERENCE LAWS")
    print("-" * 80)

    # Law I: Row 1 and Row 11 of Omega_L are identical
    assert Omega_L.row(1) == Omega_L.row(11)
    assert list(Omega_K.row(1) - Omega_K.row(11)) == [3450, 44160, 93150, 44160, 3450, 0]

    # Law II: Row 4 and Row 6 of Omega_K are identical; Omega_L diff is 576 * (1, -4, 6, -4, 1)
    assert Omega_K.row(4) == Omega_K.row(6)
    assert list(Omega_L.row(6) - Omega_L.row(4)) == [576, -2304, 3456, -2304, 576]

    # Law III: Mode 5 off-diagonal F'' transparency
    c_vec = sp.Matrix([[4800, 61440, 129600, 61440, 4800]])
    assert Omega_L.row(5) == c_vec

    # Law IV: Harmonic & Quartic row sums
    for i in range(11):
        assert sum(Omega_K.row(i)) == 0
    assert sum(Omega_K.row(11)) == -188370
    for i in [1, 2, 3, 4, 5, 6, 7, 8, 9, 11]:
        assert sum(Omega_L.row(i)) == 262080
    assert sum(Omega_L.row(10)) == 504000

    # Law V & VI: Trace and Supertrace
    d_vec = sp.Matrix([[sp.Rational(shell_sizes[s] * s, 32) for s in int_shells]])
    mult_row = sp.Matrix(1, 12, expected_multiplicities)
    assert mult_row * (Omega_K - sp.ones(12, 1) * d_vec) == sp.zeros(1, 6)
    assert mult_row * (Omega_L - sp.ones(12, 1) * c_vec) == sp.zeros(1, 5)

    parity_mult_row = sp.Matrix(1, 12, [(-1 if i % 2 == 0 else 1) * expected_multiplicities[i] for i in range(12)])
    assert list(parity_mult_row * Omega_K) == [0, 0, 0, 0, 0, -4520880]
    assert list(parity_mult_row * Omega_L) == [0, 0, 0, 0, 0]
    print("[OK] All Six Universal Conservation & Difference Laws (I-VI) certified.")

    # ==========================================================================
    # 8. SPHERICAL 11-DESIGN POLYNOMIAL LADDER & MODE-ISOLATING POLYNOMIALS
    # ==========================================================================
    print("\n[8] CERTIFYING SPHERICAL 11-DESIGN LADDER & MODE-ISOLATING POLYNOMIALS")
    print("-" * 80)

    T_poly = sp.zeros(11, 11)
    for k in range(1, 12):
        jp = sp.Matrix([-k * (s**(k - 1)) for s in int_shells])
        jpp = sp.Matrix([k * (k - 1) * (s**(k - 2) if k >= 2 else 0) for s in curved_shells])
        lam = Omega_K * jp + Omega_L * jpp
        for row_idx, mode_i in enumerate(range(11, 0, -1)):
            T_poly[row_idx, k - 1] = lam[mode_i]
            if row_idx > k - 1:
                assert T_poly[row_idx, k - 1] == 0  # Strictly upper-triangular!

    assert T_poly.is_upper
    T_poly_inv = T_poly.inv()
    s_sym = sp.Symbol('s')

    for k in range(1, 12):
        mode_i = 12 - k
        col = T_poly_inv[:, k - 1]
        lead = col[k - 1]
        poly_expr = sum((col[deg] / lead) * s_sym**(deg + 1) for deg in range(k))
        print(f"  k={k:2d} (Mode {mode_i:2d}, dim {expected_multiplicities[mode_i]:7d}): P_{k}(s) = {poly_expr}")

    elapsed = time.time() - t_start
    print("\n" + "=" * 80)
    print(f"ALL EXACT RATIONAL (QQ) & INTEGER (ZZ) AUDITS PASSED IN {elapsed:.2f} SECONDS")
    print("=" * 80)


if __name__ == "__main__":
    run_universal_bridge_audit()