#!/usr/bin/env python3
"""
extremal_48d_audit_consolidated.py
==============================================================================
Consolidated Exact-Arithmetic Audit for Collective Dynamics on S^47
SRFP311T1 Collaboration - Multi-Tier Verification Suite
==============================================================================
"""

import sys
import sympy as sp

# This consolidated version retains the original multi-tier exact audit and
# adds the independent quadrupole arithmetic verifier for the revised manuscript.
# Passing assertions do NOT replace the analytic proof of slice moments or Hessian invariance.


# =============================================================================
# GENERAL OPERATOR FORMULAS (Parameterized by Dimension D and Squared Radius R2)
# =============================================================================
# Energy convention: E(X) = 1/2 sum_{i != j} f(||x_i - x_j||^2), f(u) = u^-2.
# Ambient gradient: grad_{x_i} E = sum_{j != i} 2 f'(u_ij) (x_i - x_j).
# Geodesic correction: - c_f I, where c_f = (1/R2) sum_{j != i} u_ij f'(u_ij).
# For f(u) = u^-2, u * f'(u) = -2 / u^2, so c_f = - (2/R2) sum n_s / u_s^2.
# Curvature weights: mu_s = n_s * (R2^2 - s^2) / ((D - 1) * R2).

def compute_cf(shells, R2):
    """Computes the second fundamental form correction c_f over non-self shells."""
    return sp.Rational(-2, R2) * sum(sp.Rational(n, u**2) for _, n, u in shells)

def compute_stiffness(shells, D, R2):
    """Computes transverse stiffness lambda_perp, c_f, and restoring stiffness lambda_S."""
    mu = {s: sp.Rational(n * (R2**2 - s**2), (D - 1) * R2) for s, n, _ in shells}
    term1 = sum(sp.Rational(-4 * n, u**3) for s, n, u in shells)
    term2 = sum(sp.Rational(24 * mu[s], u**4) for s, n, u in shells)
    lambda_perp = term1 + term2
    cf = compute_cf(shells, R2)
    lambda_S = lambda_perp - cf
    return lambda_perp, cf, lambda_S, mu

def compute_kappa_dipole(shells, D, R2, mu):
    """Computes the dynamic dipole non-local contraction coefficient kappa_dipole."""
    terms = []
    for s, n_s, u_s in shells:
        f_prime = sp.Rational(-2, u_s**3)
        f_double_prime = sp.Rational(6, u_s**4)
        t_v = n_s - sp.Rational(mu[s], R2)
        t_d = sp.Rational(s, R2) * mu[s]
        terms.append(2 * f_prime * t_v + 4 * f_double_prime * t_d)
    return sum(terms)

def gegenbauer(n, a, var):
    """Gegenbauer polynomial recurrence C_n^(a)(t)."""
    if n == 0: return sp.Integer(1)
    if n == 1: return 2 * a * var
    c0, c1 = sp.Integer(1), 2 * a * var
    for k in range(2, n + 1):
        c2 = sp.simplify((2 * (k + a - 1) * var * c1 - (k + 2 * a - 2) * c0) / k)
        c0, c1 = c1, c2
    return c1

# =============================================================================
# TIER 0: FULL BRUTE-FORCE HESSIAN BENCHMARK (OCTAHEDRON ON S^2)
# =============================================================================
def run_full_octahedron_hessian_benchmark():
    """
    Constructs and diagonalizes the full 12x12 tangent Hessian on (S^2)^6
    for the regular octahedron (N=6, D=3, R^2=1) under f(u) = u^-2.
    Tests:
      1. Riemannian stationarity (grad_M E == 0 at all sites).
      2. Symmetry: H_tan = H_tan^T.
      3. Characteristic polynomial: det(z*I - H_tan) = z^3 (z - 17/8)^3 (z - 33/8)^3 (z - 6)^3.
      4. Rotational nullity: H_tan * Omega(X) = 0 for all 3 generators of so(3).
      5. Analytical dipole eigenvalue agreement: lambda_dipole = 33/8.
    """
    pts = [
        sp.Matrix([ 1,  0,  0]),
        sp.Matrix([-1,  0,  0]),
        sp.Matrix([ 0,  1,  0]),
        sp.Matrix([ 0, -1,  0]),
        sp.Matrix([ 0,  0,  1]),
        sp.Matrix([ 0,  0, -1]),
    ]
    N = 6
    D_oct = 3
    R2_oct = sp.Integer(1)
    
    # 1. Stationarity test at all sites
    for i in range(N):
        xi = pts[i]
        grad_amb = sp.zeros(3, 1)
        for j in range(N):
            if j == i: continue
            xj = pts[j]
            u_ij = (xi - xj).dot(xi - xj)
            grad_amb += 2 * sp.Rational(-2, u_ij**3) * (xi - xj)
        grad_riem = grad_amb - (grad_amb.dot(xi) / R2_oct) * xi
        assert grad_riem == sp.zeros(3, 1), f"Stationarity failed at site {i}!"

    # Orthonormal tangent bases
    tangent_bases = []
    for p in pts:
        if abs(p[0]) == 1:
            e1, e2 = sp.Matrix([0, 1, 0]), sp.Matrix([0, 0, 1])
        elif abs(p[1]) == 1:
            e1, e2 = sp.Matrix([1, 0, 0]), sp.Matrix([0, 0, 1])
        else:
            e1, e2 = sp.Matrix([1, 0, 0]), sp.Matrix([0, 1, 0])
        tangent_bases.append((e1, e2))

    # Assemble 12x12 tangent Hessian
    shells_oct = [(0, 4, 2), (-1, 1, 4)]
    cf_oct = compute_cf(shells_oct, R2_oct)
    assert cf_oct == sp.Rational(-17, 8)

    H_tan = sp.zeros(12, 12)
    for i in range(N):
        xi = pts[i]
        bi = tangent_bases[i]
        for j in range(N):
            xj = pts[j]
            bj = tangent_bases[j]
            u_ij = (xi - xj).dot(xi - xj)
            d_ij = xi - xj
            
            if i != j:
                f_p = sp.Rational(-2, u_ij**3)
                f_pp = sp.Rational(6, u_ij**4)
                amb_block = -2 * f_p * sp.eye(3) - 4 * f_pp * (d_ij * d_ij.T)
            else:
                amb_block = sp.zeros(3, 3)
                for k in range(N):
                    if k == i: continue
                    xk = pts[k]
                    u_ik = (xi - xk).dot(xi - xk)
                    d_ik = xi - xk
                    amb_block += 2 * sp.Rational(-2, u_ik**3) * sp.eye(3) + 4 * sp.Rational(6, u_ik**4) * (d_ik * d_ik.T)
                amb_block -= cf_oct * sp.eye(3)
                
            for a in range(2):
                for b in range(2):
                    H_tan[2*i + a, 2*j + b] = (bi[a].T * amb_block * bj[b])[0, 0]

    # 2. Symmetry check
    assert H_tan == H_tan.T, "Tangent Hessian is not symmetric!"

    # 3. Characteristic polynomial check
    z = sp.Symbol('z')
    charpoly = H_tan.charpoly(z).as_expr()
    expected_charpoly = (
        z**3
        * (z - sp.Rational(17, 8))**3
        * (z - sp.Rational(33, 8))**3
        * (z - 6)**3
    )
    assert sp.expand(charpoly - expected_charpoly) == 0, "Charpoly mismatch!"

    # 4. Explicit rotational null space verification for so(3)
    rot_generators = [
        sp.Matrix([[ 0,  0,  0], [ 0,  0, -1], [ 0,  1,  0]]), # x-axis
        sp.Matrix([[ 0,  0,  1], [ 0,  0,  0], [-1,  0,  0]]), # y-axis
        sp.Matrix([[ 0, -1,  0], [ 1,  0,  0], [ 0,  0,  0]]), # z-axis
    ]
    for Omega in rot_generators:
        rot_vec = sp.zeros(12, 1)
        for i in range(N):
            vi = Omega * pts[i]
            bi = tangent_bases[i]
            rot_vec[2*i]     = bi[0].dot(vi)
            rot_vec[2*i + 1] = bi[1].dot(vi)
        assert H_tan * rot_vec == sp.zeros(12, 1), "Rotational mode is not an exact zero-mode!"

    # 5. Unified formula checks
    lp_o, cf_o, ls_o, mu_o = compute_stiffness(shells_oct, D_oct, R2_oct)
    kd_o = compute_kappa_dipole(shells_oct, D_oct, R2_oct, mu_o)
    assert ls_o == sp.Rational(49, 16)
    assert kd_o == sp.Rational(-17, 16)
    assert ls_o - kd_o == sp.Rational(33, 8)
    return True

# =============================================================================
# MAIN AUDIT SUITE
# =============================================================================
def main():
    print("=" * 80)
    print("  EXACT-ARITHMETIC AUDIT ENGINE: EXTREMAL 48D COLLECTIVE DYNAMICS")
    print("  SRFP311T1 Collaboration - Multi-Tier Verification Suite")
    print("=" * 80)

    # -------------------------------------------------------------------------
    # TIER 0: FULL BRUTE-FORCE HESSIAN BENCHMARK
    # -------------------------------------------------------------------------
    print("\n[TIER 0] Full Constrained Tangent Hessian Diagonalization on S^2 (N=6)...")
    assert run_full_octahedron_hessian_benchmark()
    print("  ✓ Riemannian critical stationarity confirmed at all sites: grad_M E == 0.")
    print("  ✓ Full 12x12 tangent Hessian constructed and verified over Q.")
    print("  ✓ Operator symmetry confirmed: H_tan = H_tan^T.")
    print("  ✓ Characteristic polynomial identity verified:")
    print("    det(z*I - H_tan) = z^3 * (z - 17/8)^3 * (z - 33/8)^3 * (z - 6)^3.")
    print("  ✓ Exact rotational nullity confirmed: H_tan * Omega(X) = 0 for all Omega in so(3).")
    print("  ✓ Analytical dipole formula matches exact spectrum: lambda_dipole = 33/8.")

    # -------------------------------------------------------------------------
    # EXTERNAL MATHEMATICAL PREMISES
    # -------------------------------------------------------------------------
    print("\n[PREMISES] External Inputs from Discrete Geometry & Modular Forms:")
    print("  • Rank & Metric Sphere : D = 48, R^2 = 6 on S^47.")
    print("  • Minimal Cardinality  : N = 52,416,000 (Mallows-Sloane 1975, modular forms).")
    print("  • Inner Product Spectrum: T_* subset {-6, -3, -2, -1, 0, 1, 2, 3} (Lattice integrality).")
    print("  • Spherical Design Base: Strength t = 11 (Venkov 1984 for extremal rank 48).")

    # -------------------------------------------------------------------------
    # TIER 1: PREMISE-CONDITIONAL DESIGN INVERSION
    # -------------------------------------------------------------------------
    print("\n[TIER 1] Auditing Minimal-Shell Valencies on S^47 (Conditional on t = 11)...")
    t = sp.Symbol('t')
    alpha = sp.Rational(23, 1)
    degrees = [2, 4, 6, 8, 10, 12]
    C = {k: gegenbauer(k, alpha, t) for k in degrees}
    pts_t = [sp.Rational(0), sp.Rational(1, 6), sp.Rational(1, 3), sp.Rational(1, 2)]

    mat_rows = [[sp.Integer(1), sp.Integer(2), sp.Integer(2), sp.Integer(2)]]
    rhs_vec = [sp.Integer(52415998)]

    for k in [2, 4, 6]:
        row = [C[k].subs(t, pts_t[0]), 2*C[k].subs(t, pts_t[1]), 2*C[k].subs(t, pts_t[2]), 2*C[k].subs(t, pts_t[3])]
        mat_rows.append(row)
        rhs_vec.append(-2 * C[k].subs(t, 1))

    A = sp.Matrix(mat_rows)
    b = sp.Matrix(rhs_vec)
    det_A = A.det()

    assert det_A == sp.Rational(73695032320000, 729)
    assert sp.factorint(det_A.p) == {2: 13, 5: 4, 7: 1, 13: 2, 23: 3}
    assert sp.factorint(det_A.q) == {3: 6}

    sol = A.inv() * b
    n0, n1, n2, n3 = sol[0], sol[1], sol[2], sol[3]
    assert (n0, n1, n2, n3) == (23766960, 12608784, 1678887, 36848)
    assert n0 + 2*(n1 + n2 + n3) + 2 == 52416000

    print(f"  ✓ Non-singular moment matrix: det(A) = 73695032320000/729 != 0")
    print(f"  ✓ Solved unique valencies: n0={n0}, n1={n1}, n2={n2}, n3={n3}")

    print("\n  Auditing Gegenbauer Moment Residuals R_k:")
    for k in degrees:
        R_k = 2*C[k].subs(t, 1) + n0*C[k].subs(t, 0) + 2*n1*C[k].subs(t, sp.Rational(1, 6)) + \
              2*n2*C[k].subs(t, sp.Rational(1, 3)) + 2*n3*C[k].subs(t, sp.Rational(1, 2))
        R_norm = R_k / C[k].subs(t, 1)
        if k <= 10:
            assert sp.simplify(R_k) == 0
            print(f"  • Degree {k:2d}: R_{k} = 0 (moment identity verified under stated shell assumptions)")
        else:
            assert R_k == sp.Rational(260119995699200, 81)
            assert R_norm == sp.Rational(1111040, 244701)
            print(f"  • Degree 12: R_12 != 0 (Strict design limit: S_12^norm = 1111040/244701)")

    # -------------------------------------------------------------------------
    # TIER 2: ARITHMETIC AUDIT OF CERTIFIED MANUSCRIPT THEOREMS
    # -------------------------------------------------------------------------
    print("\n[TIER 2] Auditing Closed-Form Rational Invariants for f(u) = u^-2 (D=48, R^2=6)...")
    shells_48d = [
        ( 3, int(n3),  6),
        ( 2, int(n2),  8),
        ( 1, int(n1), 10),
        ( 0, int(n0), 12),
        (-1, int(n1), 14),
        (-2, int(n2), 16),
        (-3, int(n3), 18),
        (-6, 1,       24),
    ]
    D_48d = 48
    R2_48d = sp.Integer(6)

    # Use unified functions
    lambda_perp, c_f, lambda_S, mu_48d = compute_stiffness(shells_48d, D_48d, R2_48d)
    denom_lS = 32006016000

    for s, n, _ in shells_48d:
        assert mu_48d[s].is_integer

    assert lambda_perp == sp.Rational(-4154302592436623, 32006016000)
    assert c_f == sp.Rational(-9891249715919, 76204800)
    assert lambda_S == sp.Rational(22288249357, 32006016000)

    dim_T = 52416000 * 47
    trace_H = sp.factor(dim_T * lambda_S)
    assert trace_H == sp.Rational(13618120357127, 7938)

    print(f"  ✓ Single-particle stiffness: lambda_S = {lambda_S} > 0")
    print(f"  ✓ Tangent bundle trace     : tr(H)    = {trace_H}")

    # Dynamic Dipole Contraction
    kappa_dipole = compute_kappa_dipole(shells_48d, D_48d, R2_48d, mu_48d)
    assert kappa_dipole == sp.Rational(-4338939033931583, 32006016000)

    lambda_48 = sp.factor(lambda_S - kappa_dipole)
    gcd_cancelled = sp.gcd(lambda_S.p - kappa_dipole.p, denom_lS)
    assert gcd_cancelled == 1260
    assert lambda_48 == sp.Rational(3443620096969, 25401600)

    print(f"  ✓ Dipole contraction       : kappa_dipole = {kappa_dipole}")
    print(f"  ✓ Dipole eigenvalue        : lambda_48    = {lambda_48} > 0")
    print("    [NOTE] Rational algebra verified; operator homothety on V_48 proved in Theorem 3.4.")

    # -------------------------------------------------------------------------
    # TIER 3: EXACT QUADRUPOLE ARITHMETIC AND DIMENSION COUNT
    # -------------------------------------------------------------------------
    print("\n[TIER 3] Exact slice-formula arithmetic for the 1,175-dimensional quadrupole sector...")
    # The identities for first, second and third transverse moments on
    # fixed-inner-product slices are mathematical consequences of the spherical
    # 11-design and degree-7 interpolation.  They are NOT established merely
    # by executing this script. See the revised paper, Theorem 5.2.
    quad_diag = sp.S.Zero
    quad_off = sp.S.Zero
    quad_direct = sp.S.Zero
    rot_off = sp.S.Zero
    dip_off = sp.S.Zero
    for s, n, u in shells_48d:
        alpha = sp.Rational(s, R2_48d)
        fp = sp.Rational(-2, u**3)
        fpp = sp.Rational(6, u**4)
        mu = mu_48d[s]
        quad_diag += 2*n*alpha*fp + 4*mu*fpp
        # Independently organize the result in two algebraic ways:
        # (i) diagonal Hessian minus off-diagonal coupling,
        # (ii) cancellation of all valency-only contributions.
        quad_off += -2*fp*alpha*(n - 2*mu/R2_48d) + 4*fpp*mu*(1 - 2*alpha**2)
        quad_direct += sp.Rational(4, R2_48d)*alpha*mu*fp + 8*mu*(1 - alpha**2)*fpp
        rot_off += -2*fp*alpha*n - 4*fpp*mu
        dip_off += -2*fp*(n - mu/R2_48d) - 4*fpp*alpha*mu

    assert quad_diag == lambda_S
    assert quad_off == sp.Rational(577969260623843, 32006016000)
    lambda_quad = sp.factor(lambda_S + quad_off)
    assert lambda_quad == quad_direct
    assert lambda_quad == sp.Rational(68808517723, 3810240)
    assert sp.factor(lambda_S + rot_off) == 0
    assert sp.factor(lambda_S + dip_off) == lambda_48
    print(f"  ✓ Quadrupole contraction agrees in two formulas: lambda_1175 = {lambda_quad}")
    print("  ✓ Rotational and dipole regression identities agree with previous tiers.")

    dim_so48 = 48 * 47 // 2
    dim_dipole = 48
    dim_quad = 48 * 49 // 2 - 1
    rem_after_dipole = dim_T - dim_so48 - dim_dipole
    rem_after_quad = rem_after_dipole - dim_quad
    assert rem_after_dipole == 2463550824
    assert rem_after_quad == 2463549649
    print(f"  ✓ Mode arithmetic: 1128 rotations + 48 dipoles + 1175 quadrupoles")
    print(f"    leaves {rem_after_quad:,} unresolved dimensions.")

    # -------------------------------------------------------------------------
    # STRATIFIED AUDIT REPORT
    # -------------------------------------------------------------------------
    print("\n" + "=" * 80)
    print("  STRATIFIED AUDIT: ORIGINAL TIERS + QUADRUPOLE UPDATE")
    print("=" * 80)
    print("  [PASS] Tier 0: Exact 12x12 octahedral Hessian benchmark and spectrum.")
    print("  [PASS] Tier 1: Conditional 48D valency inversion and Gegenbauer checks.")
    print("  [PASS] Tier 2: Exact 48D stiffness, trace, and dipole arithmetic.")
    print("  [PASS] Tier 3: Exact quadrupole eigenvalue arithmetic in two formulations.")
    print("  [MATH] Slice-moment identities and invariant subspace require the paper proof;")
    print("         the checks here do not construct the full 48D Hessian.")
    print("  [OPEN] Remaining spectral bulk: 2,463,549,649 dimensions.")
    print("=" * 80)

if __name__ == "__main__":
    main()
