#!/usr/bin/env python3
"""Exact modular cubature auditor for the Leech lattice (strengths 15--171).

Public companion for "Exact Rational Spherical Designs on the Leech Lattice
through Strength 171, Harmonic-Theta Surjectivity, and Modular Sparsity
Obstructions" (2026).

COLAB: Upload this SINGLE file and run it. By default it audits ALL
listed configurations from strength 15 through 171, installing python-flint
automatically when necessary, and saving weight archives and a summary CSV.

OPTIONS (no separate installer or rational-weight archive required):
    python leech_cubature_171.py --degree 120
    python leech_cubature_171.py --degree 170   # very computationally expensive
    python leech_cubature_171.py --all          # 36 windows + all certificates
    python leech_cubature_171.py --certificates-only
    python leech_cubature_171.py --verify-121 leech_exact_weights_k120.txt.gz
    python leech_cubature_171.py --verify-170 leech_exact_weights_k170.txt.gz
    python leech_cubature_171.py --degree 170 --skip-certificates

The --verify-121 mode independently rebuilds q-series via the recurrence for
Ramanujan's tau function, checks all 271 integer modular moments, positivity,
nonzero first omitted modular moment, peak mass, and the published SHA-256.
No FLINT or floating-point calculation is needed for this verification.

The native FLINT mode performs ONE exact integer-matrix solve (FLINT-selected algorithm), checks
all modular moments EXACTLY over Q, verifies strict positivity, and exports
ALL the rational weights. It does not assume or establish minimality of shell
support. A nonzero omitted modular moment implies exact *geometric* strength
when the in-file harmonic-theta degree-172 certificate passes.

The full degree-170 archive can be independently checked with --verify-170.
The default run also executes the theta, modularity, gap, and Shell-8
orbit certificates. The theta/membership audit checks all constructed harmonics
and two extra coefficients through shell 17 even in dimension-14 degrees.
For gap certificates, --gap-backend auto prefers FLINT. On Google Colab it
installs python-flint if needed, reverting to pure Python if installation or
import fails. Outside Colab auto uses installed FLINT without installing it.
--gap-backend flint requires FLINT (and installs it); python never uses FLINT.
"""

import argparse
import csv
import gzip
import hashlib
import importlib.util
import math
import os
import subprocess
import sys
import time
from fractions import Fraction
from functools import lru_cache
from pathlib import Path

if hasattr(sys, 'set_int_max_str_digits'):
    sys.set_int_max_str_digits(1_000_000)

if not __debug__:
    raise RuntimeError('This auditor requires assertions: do not use python -O or -OO')

EXPECTED_121_SHA256 = (
    '91efe14e03ffbfd385e5a1e9118a76e68a990d0f440507034be638af9d91b3ef'
)
MAX_PRIMES_CRT = 1200
CERTIFICATE_PRIME = 2147483647
THETA_MAX_SHELL = 17

# FLINT is lazy: imports work even in environments without optional packages.
flint = fmpz = fmpq = fmpz_poly = nmod_mat = fmpz_mat = None
N_shells = basis_coefficients = None
_forms_max_shell = -1

# By default a single execution reconstructs every configured degree
# through k=170 (strength 171), just like the original master auditor.
# Set DEFAULT_RUN = 170 for ONLY strength 171, or 120 for ONLY strength 121.
# WARNING: the high-degree exact reconstruction can be very demanding.
DEFAULT_RUN = 'all'

# Window list is transcribed from Table 6.1.
MASTER_AUDIT_CONFIGURATIONS = {
    12: list(range(2, 4)),
    14: list(range(2, 4)),
    16: list(range(2, 5)),
    18: list(range(2, 6)),
    20: [2] + list(range(4, 8)),
    22: list(range(2, 8)),
    24: [2] + list(range(4, 11)),
    26: list(range(2, 11)),
    28: [2] + list(range(5, 15)),
    30: list(range(2, 15)),
    32: list(range(4, 19)),
    34: list(range(2, 19)),
    38: list(range(2, 24)),
    40: list(range(2, 27)),
    42: list(range(3, 31)),
    46: list(range(2, 36)),
    50: list(range(2, 43)),
    54: list(range(5, 54)),
    58: list(range(2, 59)),
    62: list(range(5, 71)),
    66: list(range(6, 82)),
    70: list(range(4, 90)),
    74: list(range(6, 103)),
    78: list(range(7, 116)),
    82: list(range(7, 128)),
    86: list(range(7, 141)),
    90: list(range(2, 150)),
    94: list(range(5, 167)),
    98: list(range(8, 185)),
    102: list(range(10, 203)),
    106: list(range(8, 217)),
    110: list(range(9, 235)),
    120: list(range(10, 282)),
    122: list(range(10, 291)),
    134: list(range(12, 354)),
    170: list(range(29, 590)),
}


def format_support(shells):
    """Faithful compact formatting, including arbitrary gaps in the support."""
    if not shells:
        return '(empty)'
    if list(shells) != sorted(set(shells)):
        raise ValueError('Shell support must be sorted and contain no duplicates')
    parts = []
    i = 0
    while i < len(shells):
        j = i
        while j + 1 < len(shells) and shells[j + 1] == shells[j] + 1:
            j += 1
        if j > i:
            parts.append(f'{shells[i]}..{shells[j]}')
        else:
            parts.extend(str(shells[t]) for t in range(i, j + 1))
        i = j + 1
    return ','.join(parts)


def equations_for(k_max):
    """Basis indices for Delta^2 E4^a E6^b with 4*a+6*b=k-12 (a ascending)."""
    result = []
    for k in range(12, k_max + 1, 2):
        w = k - 12
        for a in range(w // 4 + 1):
            rem = w - 4 * a
            if rem % 6 == 0:
                result.append((k, a, rem // 6))
    return result


def count_conditions(k_max):
    return len(equations_for(k_max))


def next_constrained_degree(k):
    for j in range(k + 2, k + 12, 2):
        if any(x[0] == j for x in equations_for(j)):
            return j
    raise ValueError('Could not locate next constrained degree')


def canonical_digest(shells, weights):
    payload = '\n'.join(
        f'{m}:{int(w.p)}/{int(w.q)}' for m, w in zip(shells, weights)
    )
    return hashlib.sha256(payload.encode('utf-8')).hexdigest()


def verify_published_121_archive(path):
    """Self-contained independent verification; does NOT import python-flint."""
    start = time.perf_counter()
    weights = {}
    with gzip.open(path, 'rt', encoding='utf-8') as f:
        for line in f:
            line = line.strip()
            if not line or line.startswith('#'):
                continue
            m, numerator, denominator = map(int, line.split())
            if m in weights or numerator <= 0 or denominator <= 0:
                raise AssertionError('Bad/duplicate/nonpositive rational weight')
            weights[m] = Fraction(numerator, denominator)
    assert sorted(weights) == list(range(10, 282)), 'Unexpected shell set'
    assert weights[10] == 1, 'Expected W_10 = 1'
    payload = '\n'.join(
        f'{m}:{weights[m].numerator}/{weights[m].denominator}' for m in sorted(weights)
    )
    digest = hashlib.sha256(payload.encode('utf-8')).hexdigest()
    assert digest == EXPECTED_121_SHA256, 'Published certificate hash mismatch'

    nmax = 282
    sig1, sig3, sig5, sig11 = ([0] * nmax for _ in range(4))
    for d in range(1, nmax):
        for n in range(d, nmax, d):
            sig1[n] += d
            sig3[n] += d**3
            sig5[n] += d**5
            sig11[n] += d**11

    # Independent of the CRT reconstruction's Euler-pentagonal construction:
    # n*tau(n) = tau(n) - 24 sum_{j=1}^{n-1} sigma_1(j)*tau(n-j).
    tau = [0] * nmax
    tau[1] = 1
    for n in range(2, nmax):
        v = -24 * sum(sig1[j] * tau[n-j] for j in range(1, n))
        assert v % (n - 1) == 0
        tau[n] = v // (n-1)
    assert tau[2:6] == [-24, 252, -1472, 4830]

    E4 = [1] + [240 * sig3[n] for n in range(1, nmax)]
    E6 = [1] + [-504 * sig5[n] for n in range(1, nmax)]

    def mul(a, b):
        out = [0] * nmax
        aa = [(i, x) for i, x in enumerate(a) if x]
        bb = [(j, y) for j, y in enumerate(b) if y]
        for i, x in aa:
            for j, y in bb:
                if i + j >= nmax:
                    break
                out[i + j] += x * y
        return out

    delta2 = mul(tau, tau)
    pow4 = [[1] + [0] * (nmax-1)]
    pow6 = [[1] + [0] * (nmax-1)]
    for _ in range(27):
        pow4.append(mul(pow4[-1], E4))
    for _ in range(19):
        pow6.append(mul(pow6[-1], E6))

    # Clear a common denominator AFTER Wtilde_m = W_m*(10/m)^60.
    wtilde = {m: weights[m] * Fraction(10, m)**60 for m in weights}
    common = math.lcm(*(w.denominator for w in wtilde.values()))
    ints = {m: int(wtilde[m] * common) for m in weights}
    assert all(v > 0 for v in ints.values())

    rows = 0
    for k, a, b in equations_for(120):
        F = mul(delta2, mul(pow4[a], pow6[b]))
        exponent = (120 - k) // 2
        total = sum(ints[m] * m**exponent * F[m] for m in range(10, 282))
        assert total == 0, f'Nonzero exact moment: {(k, a, b)}'
        rows += 1
    assert rows == 271

    # A modular nonzero witness: geometric interpretation also requires
    # the separate harmonic-theta surjectivity result for k=122.
    F122 = mul(delta2, mul(pow4[26], pow6[1]))
    residual = sum(Fraction(ints[m] * F122[m], m) for m in range(10, 282))
    assert residual != 0, 'Omitted degree-122 modular witness vanished'

    N_shell = {m: 65520 * (sig11[m] - tau[m]) // 691 for m in weights}
    for m in weights:
        assert 65520 * (sig11[m] - tau[m]) % 691 == 0
    peak = max(weights, key=lambda m: weights[m] * N_shell[m])
    assert peak == 128
    print('PASS: 272 positive rational weights; normalization W_10=1')
    print('PASS: 271 independent, exact modular moment equations')
    print('PASS: nonzero degree-122 modular witness')
    print('PASS: exact peak probability-mass shell S_128')
    print('PASS: archive SHA-256:', digest)
    print(f'Elapsed: {time.perf_counter()-start:.2f} seconds')


# All FLINT objects are initialized lazily so --verify-121 and --list work
# without third-party packages or silent pip installation.
def setup_flint(install_missing=True):
    """Initialize FLINT lazily, optionally without installing anything.

    install_missing=False only checks for an existing installation.
    Reconstruction and explicit FLINT mode retain automatic installation.
    """
    global flint, fmpz, fmpq, fmpz_poly, nmod_mat, fmpz_mat
    if flint is not None:
        return True
    try:
        import flint as _flint
    except ImportError:
        if not install_missing:
            return False
        print('[setup] python-flint is missing. Installing it automatically...', flush=True)
        try:
            subprocess.check_call([
                sys.executable, '-m', 'pip', 'install',
                '--disable-pip-version-check', '-q', 'python-flint',
            ])
        except subprocess.CalledProcessError as exc:
            raise RuntimeError(
                'Cannot install python-flint in this runtime. Check internet access '
                'or run --certificates-only using --gap-backend python.'
            ) from exc
        import importlib
        importlib.invalidate_caches()
        try:
            _flint = importlib.import_module('flint')
        except ImportError as exc:
            raise RuntimeError(
                'python-flint was installed but cannot be imported. Restart the '
                'Colab runtime and rerun.'
            ) from exc
    from flint import (
        fmpz as _z, fmpq as _q, fmpz_poly as _poly,
        nmod_mat as _nmod, fmpz_mat as _imat,
    )
    flint, fmpz, fmpq = _flint, _z, _q
    fmpz_poly, nmod_mat, fmpz_mat = _poly, _nmod, _imat
    if hasattr(flint, 'set_num_threads'):
        flint.set_num_threads(2)
    print(f'[setup] python-flint {getattr(flint, "__version__", "unknown")} ready.',
          flush=True)
    return True

def rational_reconstruct(a, modulus):
    """Balanced rational reconstruction with a congruence and size audit."""
    n = int(modulus)
    residue = int(a) % n
    if not residue:
        return fmpq(0)
    bound = math.isqrt((n - 1) // 2)
    r0, r1 = n, residue
    s0, s1 = 0, 1
    while r1 > bound:
        q = r0 // r1
        r0, r1 = r1, r0 - q * r1
        s0, s1 = s1, s0 - q * s1
    if s1 < 0:
        r1, s1 = -r1, -s1
    if not (0 < s1 <= bound and abs(r1) <= bound):
        return None
    if math.gcd(r1, s1) != 1 or (r1 - residue * s1) % n:
        return None
    return fmpq(fmpz(r1), fmpz(s1))


def prime_generator():
    p = (1 << 60) - 33
    while True:
        if fmpz(p).is_prime():
            yield p
        p -= 2


def setup_forms(max_shell):
    """Exact E4, E6, Delta and shell-cardinality coefficients."""
    global N_shells, basis_coefficients, _forms_max_shell
    if _forms_max_shell >= max_shell:
        return
    setup_flint()
    nmax = max_shell + 1
    sig3, sig5, sig11 = ([0] * nmax for _ in range(3))
    for d in range(1, nmax):
        for n in range(d, nmax, d):
            sig3[n] += d**3
            sig5[n] += d**5
            sig11[n] += d**11
    E4 = fmpz_poly([1] + [240 * sig3[n] for n in range(1, nmax)])
    E6 = fmpz_poly([1] + [-504 * sig5[n] for n in range(1, nmax)])

    # Euler pentagonal formula for (q;q)_infty, then Delta=q*(q;q)_infty^24.
    pent = [0] * nmax
    pent[0] = 1
    for j in range(1, math.isqrt(2 * nmax) + 3):
        p1, p2 = j * (3*j-1)//2, j * (3*j+1)//2
        sgn = -1 if j % 2 else 1
        if p1 < nmax:
            pent[p1] = sgn
        if p2 < nmax:
            pent[p2] = sgn
    eta = fmpz_poly(pent)
    eta2 = (eta * eta).truncate(nmax)
    eta4 = (eta2 * eta2).truncate(nmax)
    eta8 = (eta4 * eta4).truncate(nmax)
    eta16 = (eta8 * eta8).truncate(nmax)
    eta24 = (eta16 * eta8).truncate(nmax)
    delta = fmpz_poly([0] + [int(eta24[i]) for i in range(nmax-1)])
    delta2 = (delta * delta).truncate(nmax)
    assert int(delta[1]) == 1 and int(delta[2]) == -24
    assert int(delta2[8]) == 4_857_920

    N_shells = [0] * nmax
    for m in range(2, nmax):
        raw = 65520 * (sig11[m] - int(delta[m]))
        assert raw % 691 == 0
        N_shells[m] = raw // 691
    assert N_shells[2] == 196560 and N_shells[3] == 16773120

    rows = equations_for(172)
    max_a, max_b = max(r[1] for r in rows), max(r[2] for r in rows)
    e4pow = [fmpz_poly([1])]
    e6pow = [fmpz_poly([1])]
    for _ in range(max_a):
        e4pow.append((e4pow[-1] * E4).truncate(nmax))
    for _ in range(max_b):
        e6pow.append((e6pow[-1] * E6).truncate(nmax))

    @lru_cache(maxsize=None)
    def _basis_coefficients(a, b):
        F = (delta2 * (e4pow[a] * e6pow[b]).truncate(nmax)).truncate(nmax)
        return [int(F[i]) for i in range(nmax)]
    basis_coefficients = _basis_coefficients
    _forms_max_shell = max_shell


def ensure_forms(max_shell):
    """Make audit_degree callable directly after importing the module."""
    if _forms_max_shell < max_shell:
        setup_forms(max_shell)


def exact_moment(weights, coeffs, shells, exp):
    return sum((w * fmpq(coeffs[j], (2 * shells[j])**exp)
                for j, w in enumerate(weights)), fmpq(0))


def export_weights(path, shells, weights, degree):
    path.parent.mkdir(parents=True, exist_ok=True)
    with gzip.open(path, 'wt', encoding='utf-8') as out:
        out.write(f'# Degree k={degree}; normalized W_{shells[0]}=1\n')
        out.write('# shell numerator denominator\n')
        for m, w in zip(shells, weights):
            out.write(f'{m} {int(w.p)} {int(w.q)}\n')


def audit_degree(target, shells, output_dir, max_primes, solver="native",
                 cross_check_unscaled=False):
    """Reconstruct and certify one configured support; initialization is lazy.

    cross_check_unscaled repeats the algebraically equivalent original moment
    equations, primarily as a diagnostic for the native integer scaling code.
    """
    ensure_forms(max(shells))
    start = time.perf_counter()
    eq = equations_for(target)
    C = len(eq)
    if len(shells) != C + 1:
        raise RuntimeError(f'Configuration k={target}: {len(shells)} shells, expected {C+1}')
    next_k = next_constrained_degree(target)
    omitted_eq = [x for x in equations_for(next_k) if x[0] == next_k]
    rows = [[basis_coefficients(a, b)[m] for m in shells] for k, a, b in eq]
    next_rows = [[basis_coefficients(a, b)[m] for m in shells] for k, a, b in omitted_eq]
    exps = [k // 2 for k, a, b in eq]
    exps_unique = sorted(set(exps))
    m0, M = shells[0], len(shells)
    # Normalize W_m0=1. Put K=target/2 and
    #       T_m = W_m * (m0/m)^K.
    # After cancelling the common row factor 2^{-e} m0^{-K},
    # the EXACT integer equations are
    #       sum_m T_m * a_m(F) * m^(K-e) = 0  (e=k/2).
    # This avoids modular inversions per shell, avoids large rational
    # matrix entries and allows the highly optimized native FLINT solver.
    K = target // 2
    scalar_rows = []
    for row, e in zip(rows, exps):
        power = K - e
        scalar_rows.append([c * pow(m, power) for c, m in zip(row, shells)])

    if solver == 'native':
        # Native FLINT fmpz_mat.solve chooses its internal exact algorithm. Only ONE exact solve is needed.
        # Constructor accepts (nrows, ncols, flattened entries).
        print(f'  [native] constructing {C} x {C} integer system...', flush=True)
        mat = fmpz_mat(C, C, [v for r in scalar_rows for v in r[1:]])
        rhs = fmpz_mat(C, 1, [-r[0] for r in scalar_rows])
        tsolve = time.perf_counter()
        sol = mat.solve(rhs)
        print(f'  [native] exact solve completed in {time.perf_counter()-tsolve:.1f}s; '
              'checking integer residual...', flush=True)
        # Avoid a second solve or a slow Python loop over giant fractions:
        # clear a common denominator once and let FLINT multiply matrices.
        D = fmpz(1)
        for i in range(C):
            D = fmpz(math.lcm(int(D), int(sol[i, 0].q)))
        nums = fmpz_mat(C, 1, [fmpz(sol[i, 0].p) * (D // sol[i, 0].q)
                                  for i in range(C)])
        assert mat * nums == rhs * D, 'Native integer matrix residual failed'
        t_weights = [fmpq(1)] + [sol[i, 0] for i in range(C)]
        weights = [t * fmpq(pow(m, K), pow(m0, K))
                   for t, m in zip(t_weights, shells)]
        modulus = fmpz(0)
        used = 0
    else:
        # Legacy, repeated-CRT solves: retained for cross-checks, but slower.
        residues = [fmpz(0) for _ in range(C)]
        modulus = fmpz(1)
        used = 0
        weights = None
        for p in prime_generator():
            if used >= max_primes:
                break
            ratios = [(m0 * pow(m, -1, p)) % p for m in shells[1:]]
            factor = {e: [pow(r, e, p) for r in ratios] for e in exps_unique}
            A = nmod_mat(C, C, [0] * (C * C), p)
            B = nmod_mat(C, 1, [0] * C, p)
            for i, e in enumerate(exps):
                B[i, 0] = -rows[i][0] % p
                mult = factor[e]
                for j in range(C):
                    A[i, j] = rows[i][j+1] * mult[j] % p
            try:
                solution = A.solve(B)
            except ZeroDivisionError:
                continue
            values = [int(solution[i, 0]) for i in range(C)]
            if modulus == 1:
                residues = [fmpz(v) for v in values]
                modulus = fmpz(p)
            else:
                inverse = pow(int(modulus % p), -1, p)
                for i, value in enumerate(values):
                    difference = (value - int(residues[i] % p)) % p
                    residues[i] += fmpz(difference * inverse % p) * modulus
                modulus *= p
            used += 1
            check_step = 5 if C <= 10 else (10 if C <= 50 else 20)
            if used % check_step:
                continue
            if rational_reconstruct(residues[0], modulus) is None:
                continue
            if rational_reconstruct(residues[-1], modulus) is None:
                continue
            candidate = [rational_reconstruct(x, modulus) for x in residues]
            if any(x is None for x in candidate):
                continue
            trial = [fmpq(1)] + candidate
            if all(exact_moment(trial, row, shells, e) == 0
                   for row, e in zip(rows, exps)):
                weights = trial
                break
        if weights is None:
            raise RuntimeError(f'k={target}: CRT incomplete after {used} usable primes')

    positive = all(w > 0 for w in weights)
    # The native integer residual is exactly equivalent to the unscaled
    # rational moment system. A separate direct check is optional because it
    # can be prohibitively expensive for very large rational archives.
    zero = (True if solver == 'native' else all(
        exact_moment(weights, row, shells, e) == 0
        for row, e in zip(rows, exps)))
    if cross_check_unscaled:
        zero = zero and all(
            exact_moment(weights, row, shells, e) == 0
            for row, e in zip(rows, exps))
    omitted = [exact_moment(weights, row, shells, next_k // 2) for row in next_rows]
    nonzero = any(x != 0 for x in omitted)
    common_den = 1
    for w in weights:
        common_den = math.lcm(common_den, int(w.q))
    max_den = max(int(w.q) for w in weights)
    # EXACT comparison, not float(w)*N_m, which can round or overflow.
    peak_i = max(range(M), key=lambda j: weights[j] * N_shells[shells[j]])
    sha = canonical_digest(shells, weights)
    if target == 120 and sha != EXPECTED_121_SHA256:
        raise AssertionError('Degree-120 reconstructed weights differ from published SHA-256')
    passed = positive and zero and nonzero
    if not passed:
        raise AssertionError(f'k={target}: strict positivity / moments / omitted witness failed')
    path = output_dir / f'leech_exact_weights_k{target}.txt.gz'
    export_weights(path, shells, weights, target)
    return {
        'degree': target,
        'strength': 15 if target in (12, 14) else target+1,
        'conditions': C,
        'shells': M,
        'window': format_support(shells),
        'positive': positive,
        'moments_zero': zero,
        'first_omitted_degree': next_k,
        'first_omitted_nonzero': nonzero,
        'max_denominator_digits': len(str(max_den)),
        'max_denominator_bits': max_den.bit_length(),
        'common_denominator_digits': len(str(common_den)),
        'common_denominator_bits': common_den.bit_length(),
        'peak_mass_shell': shells[peak_i],
        'canonical_sha256': sha,
        'usable_crt_primes': used if solver == 'crt' else 'native-solve',
        'crt_modulus_bits': modulus.bit_length() if solver == 'crt' else 'n/a',
        'weights_file': str(path),
        'runtime_seconds': round(time.perf_counter()-start, 2),
        'status': 'PASS',
    }


# =============================================================================
# 6. IN-FILE MATHEMATICAL CERTIFICATES -- no companion scripts required
# =============================================================================

EXPECTED_171_SHA256 = '235c56f911c9f414a34804a07b90551a607b311c0b47fdb4d1a769e07a43399b'


def eval_real_complex_power_mod(u, v, D, k, p=CERTIFICATE_PRIME):
    """Real part of (u + i*sqrt(D)*v)**k modulo the certificate prime."""
    u %= p
    v %= p
    D %= p
    if v == 0:
        return pow(u, k, p)
    if u == 0:
        return pow((-D * v * v) % p, k // 2, p) if k % 2 == 0 else 0
    real, imag = 1, 0
    while k:
        if k & 1:
            real, imag = ((real*u - D*imag*v) % p,
                          (real*v + imag*u) % p)
        u, v = ((u*u - D*v*v) % p, 2*u*v % p)
        k >>= 1
    return real


def eval_B3_harmonic(x1, x2, x3, a, b, k, p=CERTIFICATE_PRIME):
    """Signed-permutation sum; repeated coordinates retain multiplicity 6."""
    from itertools import permutations
    coords = (x1, x2, x3)
    distinct = set(permutations(coords))
    multiplicity = 6 // len(distinct)
    D = a*a + b*b
    total = 0
    for y1, y2, y3 in distinct:
        plus = eval_real_complex_power_mod(a*y1 + b*y2, y3, D, k, p)
        minus = plus if b*y2 == 0 else eval_real_complex_power_mod(
            a*y1 - b*y2, y3, D, k, p)
        total += plus + minus
    return (total * multiplicity) % p


def certify_theta():
    """Finite-field theta-surjectivity determinant certificate for all even k <= 172.

    Uses signed-permutation-symmetrized 3-coordinate harmonics and the Golay
    compression coefficients; independent of FLINT and of cubature weights.

    IMPORTANT: eval_B3_harmonic computes the signed-permutation symmetrization
        P_{k,b}(x) = sum_{sigma in S3} sum_{eps in {+1,-1}}
          Re((x_sigma1 + eps*b*x_sigma2 + i*sqrt(1+b*b)*x_sigma3)**k).
    It does NOT compute the unsymmetrized H_{k,b} alone. P_{k,b} is harmonic.
    Co0-averaging P_{k,b} leaves every lattice-shell sum unchanged, so the
    resulting series belongs to the image of the theta map on Co0-invariants.
    The integer coordinates used here are scaled by sqrt(8) relative to Leech
    coordinates; for each even k, theta coefficients differ by 8**(-k//2),
    a nonzero scalar modulo p.

    All arithmetic is exact; no external libraries are required.
    """
    import itertools

    t0 = time.time()
    # Dimension d<=14 needs shells 2..15 for the determinant; shells 16,17
    # provide TWO genuinely overdetermined checks for the highest degrees.
    max_m = THETA_MAX_SHELL
    max_e16 = 16 * max_m
    p_mod = CERTIFICATE_PRIME

    def theta_1d_zero(r, sign_k):
        out = {}
        for k in range(-10, 11):
            val = 4*k + r
            e16 = val * val
            if e16 <= max_e16:
                out[e16] = out.get(e16, 0) + (sign_k ** (k & 1))
        return out

    def poly_mul(A, B):
        out = {}
        for e1, v1 in A.items():
            if not v1:
                continue
            for e2, v2 in B.items():
                if e1 + e2 <= max_e16 and v2:
                    out[e1 + e2] = out.get(e1 + e2, 0) + v1 * v2
        return out

    def poly_pow(A, exp):
        res = {0: 1}
        base = A
        e = exp
        while e > 0:
            if e & 1:
                res = poly_mul(res, base)
            base = poly_mul(base, base)
            e >>= 1
        return res

    # 1. Precompute 21-coordinate Golay backgrounds for s = c_1 + c_2 + c_3 in {0, 1, 2, 3}:
    t0_p, t0_n = theta_1d_zero(0, +1), theta_1d_zero(0, -1)
    t2_p = theta_1d_zero(2, +1)
    t1_p, t1_n = theta_1d_zero(1, +1), theta_1d_zero(1, -1)

    bg_ep = [{} for _ in range(4)]
    for s in range(4):
        for W, N_W in [(0, 1), (8, 759), (12, 2576), (16, 759), (24, 1)]:
            if 0 <= W - s <= 21:
                cnt = (N_W * math.comb(21, W - s)) // math.comb(24, W)
                if cnt:
                    term21 = poly_mul(poly_pow(t0_p, 21 - (W - s)), poly_pow(t2_p, W - s))
                    for e, v in term21.items():
                        bg_ep[s][e] = bg_ep[s].get(e, 0) + cnt * v
    bg_en = poly_pow(t0_n, 21)
    bg_op = poly_pow(t1_p, 21)
    bg_on = poly_pow(t1_n, 21)

    # 2. Compress the 3D projections into unordered nonnegative coordinate triples:
    def points_1d(r, sign_k):
        pts = {}
        for k in range(-10, 11):
            x = 4*k + r
            if x*x <= max_e16:
                pts[abs(x)] = pts.get(abs(x), 0) + (sign_k ** (k & 1))
        return [(ax, ax*ax, w) for ax, w in pts.items() if w != 0]

    pts_0p, pts_0n = points_1d(0, +1), points_1d(0, -1)
    pts_2p = points_1d(2, +1)
    pts_1p, pts_1n = points_1d(1, +1), points_1d(1, -1)

    def build_3d_list(L1, L2, L3):
        out = {}
        for x1, e1, w1 in L1:
            for x2, e2, w2 in L2:
                if e1 + e2 > max_e16:
                    continue
                for x3, e3, w3 in L3:
                    if e1 + e2 + e3 <= max_e16:
                        out[(x1, x2, x3)] = out.get((x1, x2, x3), 0) + w1 * w2 * w3
        return [(x1, x2, x3, x1*x1+x2*x2+x3*x3, w) for (x1, x2, x3), w in out.items() if w != 0]

    point_shell_weights = {}
    def add_contributions(P_list, bg_dict, factor):
        for x1, x2, x3, e3, w3 in P_list:
            key = tuple(sorted((x1, x2, x3)))
            if key not in point_shell_weights:
                point_shell_weights[key] = [0] * (max_m + 1)
            arr = point_shell_weights[key]
            for m in range(2, max_m + 1):
                rem_e = 16 * m - e3
                if rem_e in bg_dict:
                    arr[m] += factor * w3 * bg_dict[rem_e]

    for s in range(4):
        for c1, c2, c3 in itertools.product((0, 1), repeat=3):
            if c1 + c2 + c3 == s:
                L1 = pts_2p if c1 else pts_0p
                L2 = pts_2p if c2 else pts_0p
                L3 = pts_2p if c3 else pts_0p
                add_contributions(build_3d_list(L1, L2, L3), bg_ep[s], 1)

    add_contributions(build_3d_list(pts_0n, pts_0n, pts_0n), bg_en, 1)
    add_contributions(build_3d_list(pts_1p, pts_1p, pts_1p), bg_op, 4096)
    add_contributions(build_3d_list(pts_1n, pts_1n, pts_1n), bg_on, -4096)
    assert len(point_shell_weights) == 158, (
        'Unexpected number of compressed coordinate triples', len(point_shell_weights))
    for key, arr in point_shell_weights.items():
        assert all(v % 2 == 0 for v in arr), "Nonintegral parity projection"
        point_shell_weights[key] = [v // 2 for v in arr]

    # Sanity check: verify degree-0 shell cardinalities N_2..N_9 match Table 2.1:
    N_check = [sum(arr[m] for arr in point_shell_weights.values()) for m in range(2, 10)]
    assert N_check == [
        196560, 16773120, 398034000, 4629381120,
        34417656000, 187489935360, 814879774800, 2975551488000
    ]

    # Independent Ramanujan-tau recurrence verifies *every* available shell
    # count, including the two newly added shells 16 and 17. No FLINT needed.
    sigma1 = [sum(d for d in range(1, n + 1) if n % d == 0)
              for n in range(max_m + 1)]
    sigma11 = [sum(d**11 for d in range(1, n + 1) if n % d == 0)
               for n in range(max_m + 1)]
    tau = [0] * (max_m + 1)
    tau[1] = 1
    for n in range(2, max_m + 1):
        num = -24 * sum(sigma1[j] * tau[n - j] for j in range(1, n))
        assert num % (n - 1) == 0
        tau[n] = num // (n - 1)
    for m in range(2, max_m + 1):
        numerator = 65520 * (sigma11[m] - tau[m])
        assert numerator % 691 == 0
        expected_count = numerator // 691
        observed_count = sum(arr[m] for arr in point_shell_weights.values())
        assert observed_count == expected_count, (
            'Theta compression shell cardinality mismatch', m,
            observed_count, expected_count)

    # Check the optimized evaluator against a different, binomial formula.
    from itertools import permutations
    for coords, b, k in (
        ((0, 1, 2), 2, 12), ((1, 3, 3), 5, 168),
        ((0, 0, 4), 9, 172), ((2, 5, 7), 14, 170),
    ):
        D = 1 + b*b
        reference = 0
        for y1, y2, y3 in permutations(coords):
            for u in (y1 + b*y2, y1 - b*y2):
                reference += sum(
                    math.comb(k, 2*j) * pow(u, k - 2*j, p_mod) *
                    pow(-D*y3*y3, j, p_mod)
                    for j in range(k//2 + 1))
        optimized = eval_B3_harmonic(*coords, 1, b, k, p_mod)
        assert optimized == reference % p_mod, (
            'Harmonic evaluator disagreement', coords, b, k)

    def dim_M(w):
        if w < 0 or w == 2:
            return 0
        return w // 12 if w % 12 == 2 else w // 12 + 1

    def det_mod_p(M, p):
        k = len(M)
        A = [r[:] for r in M]
        det = 1
        for col in range(k):
            piv = next((r for r in range(col, k) if A[r][col]), None)
            if piv is None:
                return 0
            if piv != col:
                A[col], A[piv] = A[piv], A[col]
                det = -det
            h = A[col][col]
            det = (det * h) % p
            inv = pow(h, -1, p)
            for r in range(col + 1, k):
                if A[r][col]:
                    fac = (A[r][col] * inv) % p
                    for c in range(col + 1, k):
                        A[r][c] = (A[r][c] - fac * A[col][c]) % p
                    A[r][col] = 0
        return det % p

    ab_list = [(1, b) for b in range(2, 22)]
    det_summary = {}
    theta_coefficients = {}
    for k in range(12, 173, 2):
        d_k = dim_M(k - 12)
        if d_k == 0:
            continue
        full_rows = []
        for a, b in ab_list[:d_k]:
            row = [0] * (max_m - 1)  # row[j] corresponds to shell m=j+2
            for (x1, x2, x3), sh_weights in point_shell_weights.items():
                val = eval_B3_harmonic(x1, x2, x3, a, b, k, p_mod)
                if val:
                    for idx, w in enumerate(sh_weights[2:]):
                        row[idx] += val * w
            full_rows.append([v % p_mod for v in row])
        M_k = [row[:d_k] for row in full_rows]
        det_k = det_mod_p(M_k, p_mod)
        assert det_k != 0, f'Surjectivity failed at k={k}'
        det_summary[k] = det_k
        theta_coefficients[k] = full_rows

    assert len(det_summary) == 80
    print(f'NONZERO DETERMINANTS in {time.time()-t0:.2f}s: '
          'theta map surjective for all 80 nontrivial even degrees 12..172')
    print('Sample determinants modulo 2147483647:')
    for k_sample in [12, 24, 62, 120, 122, 170, 172]:
        print(f'  k={k_sample:3d} (dim={dim_M(k_sample-12):2d}): '
              f'det(M_{k_sample}) mod p = {det_summary[k_sample]}')

    return {
        'points': point_shell_weights, 'dim_M': dim_M,
        'determinants': det_summary, 'coefficients': theta_coefficients,
        'max_m': max_m, 'prime': p_mod,
    }


def certify_theta_modularity(theta_certificate):
    """Test *every* constructed harmonic theta series against modular q-forms.

    The harmonic coefficients are computed once by certify_theta, while the
    modular forms below are reconstructed independently from E4, E6, and
    Delta=(E4**3-E6**2)/1728. Every degree, every determinant row and every
    coefficient outside the fitted d-dimensional window is compared modulo p.
    In dimension 14, both shells 16 and 17 are verified for all 14 rows.
    """
    p = theta_certificate['prime']
    dim_M = theta_certificate['dim_M']
    N = theta_certificate['max_m'] + 1
    theta_coefficients = theta_certificate['coefficients']
    assert N >= 18, 'Need at least two extra shells at maximal dimension 14'

    def conv(u, v):
        w = [0] * N
        for i, a in enumerate(u):
            if a:
                for j, b in enumerate(v[:N - i]):
                    if b:
                        w[i + j] = (w[i + j] + a*b) % p
        return w

    E4 = [1] + [240 * sum(z**3 for z in range(1, n + 1)
                          if n % z == 0) % p for n in range(1, N)]
    E6 = [1] + [-504 * sum(z**5 for z in range(1, n + 1)
                           if n % z == 0) % p for n in range(1, N)]
    inv1728 = pow(1728, -1, p)
    Delta = [(a - b) * inv1728 % p for a, b in zip(
        conv(conv(E4, E4), E4), conv(E6, E6))]
    assert Delta[0] == 0 and Delta[1] == 1 and Delta[2] == p - 24
    D2 = conv(Delta, Delta)
    assert D2[8] == 4_857_920
    e4powers = [[1] + [0] * (N - 1)]
    e6powers = [[1] + [0] * (N - 1)]
    for _ in range(40):
        e4powers.append(conv(e4powers[-1], E4))
    for _ in range(30):
        e6powers.append(conv(e6powers[-1], E6))

    def solve(mat, b):
        n = len(mat)
        A = [list(row) + [b[i]] for i, row in enumerate(mat)]
        for c in range(n):
            i = next((r for r in range(c, n) if A[r][c]), None)
            if i is None:
                raise AssertionError(f'Singular modular basis at column {c}')
            A[i], A[c] = A[c], A[i]
            inv = pow(A[c][c], -1, p)
            A[c] = [(v * inv) % p for v in A[c]]
            for r in range(n):
                if r != c and A[r][c]:
                    factor = A[r][c]
                    A[r] = [(x - factor*y) % p for x, y in zip(A[r], A[c])]
        return [row[-1] for row in A]

    total_checks = 0
    total_rows = 0
    for k in range(12, 173, 2):
        d_k = dim_M(k - 12)
        if d_k == 0:
            continue
        forms = [conv(D2, conv(e4powers[a], e6powers[b]))
                 for a in range((k - 12) // 4 + 1)
                 for b in range((k - 12) // 6 + 1)
                 if 4*a + 6*b == k - 12]
        assert len(forms) == d_k, (k, len(forms), d_k)
        basis = [[F[m] for F in forms] for m in range(2, d_k + 2)]
        rows = theta_coefficients[k]
        assert len(rows) == d_k
        checks = 0
        for row_index, coeff in enumerate(rows):
            assert len(coeff) == N - 2
            c = solve(basis, coeff[:d_k])
            for m in range(d_k + 2, N):
                fitted = sum(c[j] * forms[j][m] for j in range(d_k)) % p
                if coeff[m - 2] != fitted:
                    raise AssertionError(
                        f'Modularity mismatch k={k}, b={row_index + 2}, '
                        f'shell={m}, got={coeff[m - 2]}, expected={fitted}')
                checks += 1
        expected = d_k * (N - (d_k + 2))
        assert checks == expected and checks > 0, (k, checks, expected)
        total_checks += checks
        total_rows += d_k
        print(f'PASS modularity k={k:3} d={d_k:2} '
              f'full harmonic rows={d_k:2} extra coefficient checks={checks:3}')
    print(f'PASS: {total_checks} nonvacuous modularity comparisons '
          f'across {total_rows} harmonic rows')
    return {'extra_checks': total_checks, 'harmonic_rows': total_rows}

def modular_rank_nullspace(rows, p=CERTIFICATE_PRIME):
    """Compute rank and a column-oriented nullspace basis over F_p.

    Input is copied; the output basis is represented as ncols x nullity.
    Only forward elimination is used, followed by exact back substitution.
    """
    if not rows:
        raise ValueError('Matrix must have at least one row')
    nrows, ncols = len(rows), len(rows[0])
    if any(len(r) != ncols for r in rows):
        raise ValueError('Nonrectangular matrix')
    A = [[v % p for v in row] for row in rows]
    pivots = []
    rank = 0
    for col in range(ncols):
        pivot = next((r for r in range(rank, nrows) if A[r][col]), None)
        if pivot is None:
            continue
        A[rank], A[pivot] = A[pivot], A[rank]
        pr = A[rank]
        inv = pow(pr[col], -1, p)
        for c in range(col, ncols):
            pr[c] = pr[c] * inv % p
        for r in range(rank + 1, nrows):
            rr = A[r]
            factor = rr[col]
            if factor:
                rr[col] = 0
                for c in range(col + 1, ncols):
                    rr[c] = (rr[c] - factor * pr[c]) % p
        pivots.append(col)
        rank += 1
        if rank == nrows:
            break
    pivot_set = set(pivots)
    free_cols = [c for c in range(ncols) if c not in pivot_set]
    nullity = len(free_cols)
    basis = [[0] * nullity for _ in range(ncols)]
    for j, c in enumerate(free_cols):
        basis[c][j] = 1
    for r in range(rank - 1, -1, -1):
        col = pivots[r]
        for j in range(nullity):
            basis[col][j] = -sum(
                A[r][c] * basis[c][j] for c in range(col + 1, ncols)
                if basis[c][j]) % p
    return rank, basis


def modular_determinant(rows, p=CERTIFICATE_PRIME):
    """Square-matrix determinant over F_p, with exact pivoting."""
    n = len(rows)
    if any(len(row) != n for row in rows):
        raise ValueError('Determinant requires a square matrix')
    A = [[v % p for v in row] for row in rows]
    det = 1
    for col in range(n):
        pivot = next((r for r in range(col, n) if A[r][col]), None)
        if pivot is None:
            return 0
        if pivot != col:
            A[col], A[pivot] = A[pivot], A[col]
            det = -det
        pr = A[col]
        det = det * pr[col] % p
        inv = pow(pr[col], -1, p)
        for r in range(col + 1, n):
            rr = A[r]
            factor = rr[col] * inv % p
            if factor:
                rr[col] = 0
                for c in range(col + 1, n):
                    rr[c] = (rr[c] - factor * pr[c]) % p
    return det % p


def running_in_colab():
    """Detect Colab in notebooks and in subprocesses launched with !python."""
    if os.environ.get('COLAB_RELEASE_TAG') or os.environ.get('COLAB_BACKEND_VERSION'):
        return True
    if 'google.colab' in sys.modules:
        return True
    try:
        return importlib.util.find_spec('google.colab') is not None
    except (ImportError, ValueError, AttributeError):
        return False


def select_gap_flint(backend):
    """Return whether to use FLINT, with safe fallback only in auto mode.

    In Colab auto installs FLINT when missing; outside Colab auto only checks.
    Explicit 'flint' keeps strict installation/failure semantics, while
    explicit 'python' avoids both imports and package installation.
    """
    if backend not in ('auto', 'python', 'flint'):
        raise ValueError('Unknown gap backend')
    if backend == 'python':
        return False
    if backend == 'flint':
        setup_flint(install_missing=True)
        return True
    in_colab = running_in_colab()
    try:
        return setup_flint(install_missing=in_colab)
    except (RuntimeError, ImportError, OSError) as exc:
        print(f'[gap] FLINT unavailable ({exc}); '
              'falling back to standard Python.', flush=True)
        return False


def certify_gap(backend='auto'):
    """Rank, 53-shell, 13-gap, and window-support certificates over F_p.

    auto prefers FLINT and automatically installs it in Google Colab;
    installation/import failure safely falls back to pure Python. Outside
    Colab, auto uses installed FLINT only. Explicit flint strictly requires
    FLINT, and explicit python always uses standard Python.
    Both backends check the same exact finite-field statements and constants.
    """
    use_flint = select_gap_flint(backend)
    print(f'[gap] backend: {"FLINT" if use_flint else "standard Python"}', flush=True)
    tstart = time.perf_counter()
    p = CERTIFICATE_PRIME
    N = 296
    S53 = [
        12, 89, 150, 168, 177, 178, 180, 189, 196, 200, 208, 212, 213, 214, 215, 218,
        220, 222, 227, 230, 235, 236, 242, 243, 246, 248, 250, 252, 253, 256, 257,
        258, 262, 267, 269, 271, 272, 273, 274, 276, 277, 281, 282, 283, 285, 286,
        287, 288, 289, 290, 291, 292, 295,
    ]
    pool = list(range(12, 296))
    assert len(S53) == 53 and len(pool) == 284
    sig3 = [0] * N
    sig5 = [0] * N
    for d in range(1, N):
        for n in range(d, N, d):
            sig3[n] = (sig3[n] + pow(d, 3, p)) % p
            sig5[n] = (sig5[n] + pow(d, 5, p)) % p
    E4 = [1] + [(240 * sig3[n]) % p for n in range(1, N)]
    E6 = [1] + [(-504 * sig5[n]) % p for n in range(1, N)]

    def mul(u, v):
        out = [0] * N
        aa = [(i, x) for i, x in enumerate(u) if x]
        bb = [(j, y) for j, y in enumerate(v) if y]
        for i, x in aa:
            for j, y in bb:
                if i + j >= N:
                    break
                out[i + j] = (out[i + j] + x*y) % p
        return out

    E4cube = mul(mul(E4, E4), E4)
    E6sq = mul(E6, E6)
    inv1728 = pow(1728, -1, p)
    Delta = [(x - y) * inv1728 % p for x, y in zip(E4cube, E6sq)]
    D2 = mul(Delta, Delta)
    assert D2[8] == 4_857_920
    e4pow = [[1] + [0] * (N - 1)]
    e6pow = [[1] + [0] * (N - 1)]
    for _ in range(27):
        e4pow.append(mul(e4pow[-1], E4))
    for _ in range(19):
        e6pow.append(mul(e6pow[-1], E6))
    coeff_rows = []
    weighted_rows = []
    for k, a, b in equations_for(120):
        F = mul(D2, mul(e4pow[a], e6pow[b]))
        coeff_rows.append([F[m] for m in pool])
        weighted_rows.append([F[m] * pow(2*m, -k // 2, p) % p for m in pool])
    assert len(weighted_rows) == 271

    if use_flint:
        A = nmod_mat(271, 284, [v for row in weighted_rows for v in row], p)
        B = nmod_mat(271, 284, [v for row in coeff_rows for v in row], p)
        assert A.rank() == B.rank() == 271
        a_basis, da = A.nullspace()
        b_basis, db = B.nullspace()
        basisA = [[int(a_basis[i, j]) for j in range(da)] for i in range(284)]
        basisB = [[int(b_basis[i, j]) for j in range(db)] for i in range(284)]
    else:
        rankA, basisA = modular_rank_nullspace(weighted_rows, p)
        rankB, basisB = modular_rank_nullspace(coeff_rows, p)
        assert rankA == rankB == 271, (rankA, rankB)
        da, db = len(basisA[0]), len(basisB[0])
    assert da == db == 13
    # Verify the returned nullspaces by direct modular residuals, independently
    # of the elimination/nullspace implementation used by either backend.
    for matrix, G, label in (
        (weighted_rows, basisA, 'A'), (coeff_rows, basisB, 'B'),
    ):
        for r, row in enumerate(matrix):
            for col in range(13):
                residual = sum(row[c] * G[c][col] for c in range(284)) % p
                if residual:
                    raise AssertionError(
                        f'{label}: nullspace residual at row {r}, col {col}')
    selected = [m - 12 for m in S53]
    equation_labels = equations_for(120)
    reference_rows = sorted(range(len(equation_labels)),
                            key=lambda r: (equation_labels[r][0], equation_labels[r][1]))[:53]
    assert len(reference_rows) == 53
    assert equation_labels[reference_rows[-1]] == (58, 1, 7)
    ad = modular_determinant([
        [weighted_rows[r][c] for c in selected] for r in reference_rows], p)
    bd = modular_determinant([
        [coeff_rows[r][c] for c in selected] for r in reference_rows], p)
    print('53-shell full-rank determinants mod p:', ad, bd, flush=True)
    assert ad == 2000892247 and bd == 773064976
    for G, label in [(basisA, 'A'), (basisB, 'B')]:
        for start in range(272):
            minor = [G[start+i][:] for i in range(13)]
            if modular_determinant(minor, p) == 0:
                raise AssertionError(f'{label}: singular 13-gap minor at shell {12+start}')
        print(f'PASS {label}: all 272 contiguous 13-shell minors nonzero mod p', flush=True)

    # For every 272-shell window, nullspace vectors supported within that
    # window form a single line, and its generator is nonzero on every shell.
    for s in range(12, 25):
        outside = [i for i, m in enumerate(pool) if not (s <= m < s + 272)]
        rank, ker = modular_rank_nullspace([basisA[i] for i in outside], p)
        assert rank == 12 and len(ker[0]) == 1
        coeff = [row[0] for row in ker]
        for i, m in enumerate(pool):
            v = sum(x*y for x, y in zip(basisA[i], coeff)) % p
            assert (v != 0) == (s <= m < s + 272), (s, m, v)
    print('PASS: pool ranks 271/271, 53-shell obstruction, 13-gap obstruction')
    print('PASS: all 13 contiguous 272-shell windows have 1D full-support kernels')
    print(f'[gap] finite-field certificate elapsed: {time.perf_counter()-tstart:.2f}s')
    return {'backend': 'flint' if use_flint else 'python', 'rank': 271,
            'nullity': 13, 'checked_gap_minors': 544, 'checked_windows': 13}

def certify_shell8_orbits():
    """Exact rational verification of the 3-orbit Co0 decomposition of Shell 8 (Theorem 9.1)."""
    def C12_11(t):
        return (
            2_648_662_016 * t**12
            - 3_972_993_024 * t**10
            + 2_128_389_120 * t**8
            - 496_624_128 * t**6
            + 49_008_960 * t**4
            - 1_633_632 * t**2
            + 8_008
        )

    # S_2 inner-product multiplicities (for u in S_2, u.y in {+-4, +-2, +-1, 0}):
    mult_S2 = {4: 1, 2: 4_600, 1: 47_104, 0: 93_150}
    Psi12_S2 = (
        C12_11(Fraction(0)) * mult_S2[0]
        + sum(2 * mult_S2[d] * C12_11(Fraction(d, 4)) for d in (1, 2, 4))
    )
    assert Psi12_S2 == 1_771_619_850

    # O_{8_B}: v_B = 1/sqrt(8)*(10, 2^7, 0^16), v_B.y in {+-6..0}
    mult_8B = {6: 8, 5: 256, 4: 2_268, 3: 9_472, 2: 23_608, 1: 39_424, 0: 46_488}
    assert mult_8B[0] + 2 * sum(mult_8B[d] for d in range(1, 7)) == 196_560
    Psi12_8B = 4096 * (
        C12_11(Fraction(0)) * mult_8B[0]
        + sum(2 * mult_8B[d] * C12_11(Fraction(d, 8)) for d in range(1, 7))
    )
    ratio_8B = Psi12_8B / Psi12_S2
    assert Psi12_8B == -3_081_078_000 and ratio_8B == Fraction(-40, 23)

    # O_{8_C}: v_C = 2y + z (y.z = -1), v_C.y' in {+-7, +-5..0}
    mult_8C = {7: 1, 5: 275, 4: 2_300, 3: 9_153, 2: 24_576, 1: 37_675, 0: 48_600}
    assert mult_8C[0] + 2 * sum(mult_8C[d] for d in (1, 2, 3, 4, 5, 7)) == 196_560
    Psi12_8C = 4096 * (
        C12_11(Fraction(0)) * mult_8C[0]
        + sum(2 * mult_8C[d] * C12_11(Fraction(d, 8)) for d in (1, 2, 3, 4, 5, 7))
    )
    ratio_8C = Psi12_8C / Psi12_S2
    assert Psi12_8C == 450_646_170_975 and ratio_8C == Fraction(11_701, 46)

    # Exact orbit cardinalities and modular partition of a_8(Delta^2) = 4,857,920:
    size_8A = 196_560
    size_8B = (398_034_000 * 16_192) // 8
    size_8C = 196_560 * 47_104
    assert (size_8A, size_8B, size_8C) == (196_560, 805_620_816_000, 9_258_762_240)
    assert size_8A + size_8B + size_8C == 814_879_774_800  # N_8

    m_8A = Fraction(size_8A, 196_560) * 4096
    m_8B = Fraction(size_8B, 196_560) * ratio_8B
    m_8C = Fraction(size_8C, 196_560) * ratio_8C
    assert (m_8A, m_8B, m_8C) == (4_096, -7_128_000, 11_981_824)
    assert m_8A + m_8B + m_8C == 4_857_920  # a_8(Delta^2)

    assert -m_8A / m_8B == Fraction(64, 111_375)
    assert -m_8C / m_8B == Fraction(187_216, 111_375)
    print('PASS: Shell 8 3-orbit decomposition, Psi_12 ratios, a_8(Delta^2)=4857920, weight ratios')


def verify_170_archive(path):
    """Independent Fourier construction, exact 560-row certificate, no solve.

    Rebuild Delta via (E4^3-E6^2)/1728 (NOT the pentagonal product used by
    the reconstruction).  Verify the whole rational-vector residual using an
    exact scaled integer matrix, positivity, omitted degree-172 witness,
    exact peak shell, and the canonical serialization digest.
    """
    from math import lcm

    setup_flint()
    tstart = time.perf_counter()
    shells = MASTER_AUDIT_CONFIGURATIONS[170]
    data = {}
    with gzip.open(path, 'rt', encoding='utf-8') as f:
        for line in f:
            line = line.strip()
            if not line or line.startswith('#'):
                continue
            m, numerator, denominator = map(int, line.split())
            if m in data or denominator <= 0:
                raise AssertionError('Duplicate shell or invalid denominator in archive')
            data[m] = Fraction(numerator, denominator)
    assert sorted(data) == shells, 'Archive has unexpected shell support'
    assert data[shells[0]] == 1, 'Normalization W_29=1 absent'
    assert all(v > 0 for v in data.values()), 'Archive includes nonpositive weights'
    serialized = '\n'.join(f'{m}:{data[m].numerator}/{data[m].denominator}' for m in shells)
    digest = hashlib.sha256(serialized.encode('utf-8')).hexdigest()
    assert digest == EXPECTED_171_SHA256, (
        f'Unexpected archive digest {digest}; inspect serialization or archive version')

    nmax = max(shells) + 1
    sigma3, sigma5, sigma11 = ([0] * nmax for _ in range(3))
    for d in range(1, nmax):
        for n in range(d, nmax, d):
            sigma3[n] += d**3
            sigma5[n] += d**5
            sigma11[n] += d**11
    E4 = fmpz_poly([1] + [240 * sigma3[n] for n in range(1, nmax)])
    E6 = fmpz_poly([1] + [-504 * sigma5[n] for n in range(1, nmax)])
    e4cube = ((E4 * E4).truncate(nmax) * E4).truncate(nmax)
    e6square = (E6 * E6).truncate(nmax)
    delta_numer = e4cube - e6square
    assert all(int(delta_numer[i]) % 1728 == 0 for i in range(nmax))
    Delta = fmpz_poly([int(delta_numer[i]) // 1728 for i in range(nmax)])
    Delta2 = (Delta * Delta).truncate(nmax)
    assert int(Delta2[8]) == 4857920

    terms = equations_for(172)
    aa, bb = max(v[1] for v in terms), max(v[2] for v in terms)
    pow4 = [fmpz_poly([1])]
    pow6 = [fmpz_poly([1])]
    for _ in range(aa):
        pow4.append((pow4[-1] * E4).truncate(nmax))
    for _ in range(bb):
        pow6.append((pow6[-1] * E6).truncate(nmax))

    # For each degree j <= 170, put K=85 and e=j/2:
    # sum_m W_m*(2m)^(-e) a_m(F) = 0
    # iff sum_m T_m*m^(K-e) a_m(F)=0 for T_m=W_m*(29/m)^K.
    K = 85
    weights = [data[m] for m in shells]
    scaled = [v * Fraction(shells[0], m)**K for v, m in zip(weights, shells)]
    D = 1
    for v in scaled:
        D = lcm(D, v.denominator)
    vec = fmpz_mat(len(shells), 1, [fmpz(v.numerator * (D // v.denominator)) for v in scaled])
    matrix_rows = []
    omitted = []
    for j, a, b in terms:
        form = (Delta2 * (pow4[a] * pow6[b]).truncate(nmax)).truncate(nmax)
        if j <= 170:
            matrix_rows.extend(int(form[m]) * m**(K - j // 2) for m in shells)
        elif j == 172:
            # For the omitted degree, use original positive rational weights.
            # A common denominator permits exact integer arithmetic, avoiding
            # accidental rounding or comparison of massive rationals as floats.
            omitted.append(form)
    rows = count_conditions(170)
    assert rows == 560
    M = fmpz_mat(rows, len(shells), matrix_rows)
    assert M * vec == fmpz_mat(rows, 1, [0] * rows), 'Nonzero exact modular residual'
    nonzero_omitted = False
    for form in omitted:
        # At degree 172, exponent K+1=86, and T_m*m^-1 gives the
        # same moment up to the shared positive power of (2m0)^-86.
        val = sum((fmpq(vec[i, 0] * int(form[shells[i]]), shells[i])
                   for i in range(len(shells))), fmpq(0))
        if val != 0:
            nonzero_omitted = True
            break
    assert nonzero_omitted, 'First omitted degree-172 moment vanished'
    Ns = []
    for m in shells:
        raw = 65520 * (sigma11[m] - int(Delta[m]))
        assert raw % 691 == 0
        Ns.append(raw // 691)
    peak = max(range(len(shells)), key=lambda i: weights[i] * Ns[i])
    assert shells[peak] == 264, 'Unexpected peak shell'
    print('PASS: strength-171 independent archive verification')
    print('PASS: 561 positive weights; 560 exact modular equations; degree-172 witness')
    print('PASS: independent Delta formula, exact S_264 peak, SHA-256=' + digest)
    print(f'Independent strength-171 certificate time: {time.perf_counter()-tstart:.1f}s')
    return digest


def main(argv=None):
    # Colab/Jupyter kernels inject '-f /path/to/kernel-....json' into sys.argv
    # when a script is executed within the notebook interpreter.  Filter only
    # this known kernel argument; other invalid CLI flags must still be errors.
    if argv is None:
        argv = sys.argv[1:]
        kernel_context = (
            'ipykernel' in sys.modules
            or 'colab_kernel_launcher' in Path(sys.argv[0]).name
        )
        if kernel_context:
            cleaned = []
            i = 0
            while i < len(argv):
                arg = argv[i]
                if (arg == '-f' and i + 1 < len(argv)
                        and argv[i + 1].endswith('.json')):
                    i += 2
                    continue
                cleaned.append(arg)
                i += 1
            argv = cleaned

    ap = argparse.ArgumentParser(description=__doc__,
                                 formatter_class=argparse.RawDescriptionHelpFormatter)
    modes = ap.add_mutually_exclusive_group()
    modes.add_argument('--degree', type=int, help='Reconstruct specified degree (e.g. 120 or 170)')
    modes.add_argument('--all', action='store_true', help='Run entire audit through strength 171 (default)')
    modes.add_argument('--verify-121', type=Path, metavar='FILE.gz',
                       help='Check published strength-121 archive using standard Python only')
    modes.add_argument('--list', action='store_true', help='List configured support windows')
    modes.add_argument('--certificates-only', action='store_true',
                       help='Check theta, modularity, gap, and Shell-8 certificates without reconstructing weights')
    modes.add_argument('--verify-170', type=Path, metavar='FILE.gz',
                       help='Independently verify strength-171 archive without solving')
    ap.add_argument('--output-dir', type=Path,
                    default=Path('/content/leech_results') if Path('/content').exists() else Path('.'),
                    help='Output folder for rational archives and CSV')
    ap.add_argument('--max-primes', type=int, default=MAX_PRIMES_CRT)
    ap.add_argument('--skip-certificates', action='store_true',
                    help='Reconstruct cubatures only; skip separate theta/gap checks')
    ap.add_argument('--solver', choices=['native', 'crt'], default='native',
                    help='native FLINT exact solve (faster, default), or legacy CRT')
    ap.add_argument('--gap-backend', choices=['auto', 'flint', 'python'], default='auto',
                    help='gap certificate: auto installs FLINT in Colab with Python fallback; flint forces FLINT; python disables FLINT')
    ap.add_argument('--cross-check-unscaled', action='store_true',
                    help='also check original unscaled rational moments (can be very slow at k=170)')
    args = ap.parse_args(argv)
    if args.verify_121 is not None:
        verify_published_121_archive(args.verify_121)
        return
    if args.verify_170 is not None:
        verify_170_archive(args.verify_170)
        return
    if args.certificates_only:
        cert = certify_theta()
        certify_theta_modularity(cert)
        certify_gap(backend=args.gap_backend)
        certify_shell8_orbits()
        print('PASS: all in-file theta / modularity / sparsity / Shell-8 certificates')
        return
    if args.list:
        for k, shells in MASTER_AUDIT_CONFIGURATIONS.items():
            print(f'k={k:3}, strength={15 if k in (12, 14) else k + 1:3}, '
                  f'C={count_conditions(k):3}, M={len(shells):3}, '
                  f'support={format_support(shells)}')
        return
    targets = (list(MASTER_AUDIT_CONFIGURATIONS)
               if args.all or (args.degree is None and DEFAULT_RUN == 'all')
               else [args.degree if args.degree is not None else int(DEFAULT_RUN)])
    invalid = [k for k in targets if k not in MASTER_AUDIT_CONFIGURATIONS]
    if invalid:
        ap.error(f'Unknown degree(s) {invalid}. Use --list.')
    if args.max_primes < 1:
        ap.error('--max-primes must be positive')

    setup_flint()
    max_shell = max(max(MASTER_AUDIT_CONFIGURATIONS[k]) for k in targets)
    setup_forms(max_shell)
    args.output_dir.mkdir(parents=True, exist_ok=True)
    csv_path = args.output_dir / 'leech_cubature_171_summary.csv'
    rows = []
    print(f'python-flint {getattr(flint, "__version__", "unknown")}; '
          f'{len(targets)} degree(s); maximum target strength '
          f'{max(15 if k in (12, 14) else k + 1 for k in targets)}; '
          f'saving complete exact weights to {args.output_dir}', flush=True)
    for k in targets:
        print(f'Reconstructing degree k={k} ...', flush=True)
        row = audit_degree(k, MASTER_AUDIT_CONFIGURATIONS[k],
                           args.output_dir, args.max_primes, args.solver,
                           cross_check_unscaled=args.cross_check_unscaled)
        rows.append(row)
        with csv_path.open('w', newline='', encoding='utf-8') as f:
            writer = csv.DictWriter(f, fieldnames=list(row.keys()))
            writer.writeheader()
            writer.writerows(rows)
        print(f'PASS k={k}; t={row["strength"]}; '
              f'peak=S_{row["peak_mass_shell"]}; SHA-256={row["canonical_sha256"]}; '
              f'weight archive={row["weights_file"]}', flush=True)
    print(f'{len(rows)}/{len(targets)} exact modular audits passed. CSV: {csv_path}')
    if not args.skip_certificates:
        print('Running independent mathematical certificates...', flush=True)
        cert = certify_theta()
        certify_theta_modularity(cert)
        certify_gap(backend=args.gap_backend)
        certify_shell8_orbits()
        print('PASS: theta surjectivity through degree 172; modularity; gap/rank obstructions; Shell-8 orbits')
        if 170 in targets:
            verify_170_archive(args.output_dir / 'leech_exact_weights_k170.txt.gz')
    print('FINISHED: completed all selected verification stages.')


if __name__ == '__main__':
    main()