#!/usr/bin/env python3
"""Leech lattice prime-shell spherical cubature: a SINGLE-FILE exact toolkit.

Python 3.9+ STANDARD LIBRARY ONLY. No modules or data files are needed for
built-in tests and small-strength constructions.

Examples:
  python leech_prime_cubatures.py examples
  python leech_prime_cubatures.py test
  python leech_prime_cubatures.py construct --strength 17 --prime-limit 11 --out new.json
  python leech_prime_cubatures.py construct --strength 33 --prime-limit 59 --out t33.json
  python leech_prime_cubatures.py construct --strength 17 --prime-limit 11 --full-dimensional
  python leech_prime_cubatures.py verify new.json
  python leech_prime_cubatures.py verify --archive /path/to/certificate_folder

Mathematics:
  Shell S_p = {x in Leech: ||x||^2 = 2p}, radially projected to S^23.
  A basis of ambient degree-j conditions is Delta^2 E4^a E6^b, where
  j is even >=12 and 4a+6b=j-12. For integer or rational per-point weights
  W_p, the exact spherical moments are
                sum_p W_p * [q^p]F / (2p)^(j/2).
  Vanishing of all those moments proves strength AT LEAST t, regardless of
  whether harmonic-theta surjectivity is known in that degree.

Cautions:
  * An omitted ambient modular moment proves EXACT geometric strength only
    if the harmonic-theta map is known to be onto in the omitted degree
    (Paper I establishes this for even degrees <=172).
  * The constructor discovers a positive prefix via exact enumeration of LP
    vertices (COMBINATORIAL small-rank backend), then purifies it by rational
    nullspace elimination to <= r+1 prime shells. Use --full-dimensional
    for the legacy <= 2r greedy-support mode. The enumeration backend is
    not a scalable implementation of the all-strength theorem.
  * No floating point is used to decide positivity or check certificates.
  * This script verifies finite rational modular moment certificates only.
    It does NOT independently establish the analytic automorphic prime-number
    theorem estimates or the manuscript's unconditional effective-asymptotic
    quasipolynomial cutoff. It also does
    not prove the external harmonic-theta surjectivity used for some exact-
    geometric-strength statements; those depend on the cited Paper I.
  * Certificate weights must be integers or exact rational strings (e.g.
    "11/7"); floats and booleans are rejected to avoid unintended rounding.

Consolidates: verify_prime_shell.py, verify_added_example.py,
construct_and_prune.py, independent_verify.py, test_all.py.
"""

import argparse
import hashlib
import itertools
import json
import math
import sys
from fractions import Fraction
from functools import lru_cache
from pathlib import Path

# The published higher-strength archives can contain weights with more than
# 4,300 decimal digits; permit those exact research certificates on Python
# versions that cap decimal integer conversions by default. Treat input files
# as trusted research data (enormous untrusted files can consume resources).
if hasattr(sys, "set_int_max_str_digits"):
    sys.set_int_max_str_digits(0)


# These nine archived regression certificates are self-contained in this file.
# Each maps strength -> (space-delimited primes, space-delimited positive ints).
BUNDLED_CERTIFICATES = {
    17: ('2 7 11',
        '1095213313760952320 2486269201588480 170444463202816'),
    19: ('2 3 7 11',
        '493462424863637504 86046934954692096 549087979331584 117105114125824'),
    21: ('2 3 7 11 13',
        '297889374606370799616000 103288063848236015164416 903673114981055770624 110524842548941556736 '
        '27803141823123709952'),
    23: ('2 3 7 11 17 19',
        '10891534632410483469038064590913536 940362549119483086124651964690432 '
        '85402890700269644762047973154816 4536865874082613138955098494976 '
        '264739090470460225273545785344 262733150541009731217706199040'),
    25: ('2 3 7 13 17 19 23 29',
        '2066884527730832215206038792042933281848407349371338752 '
        '1802483430515910430231084968795300856954608790663028736 '
        '254806491664053497390101421338552649916252254187520 '
        '111115008369243662421394554136722861427227454152704 '
        '50922404902344620336937996529169532207321345589248 '
        '5048662342752845452977546531548277659980662906880 '
        '41107721834407674049447571704728669896755032453120 '
        '10818567345691501783047800401632632263538523463680'),
    27: ('2 5 7 11 17 19 23 29 31',
        '16455877524666548932227879317560852173944805614025299638877369139200 '
        '720919047336574171029633403465540284874503320005913000000000000000 '
        '63327542528725577740403094907430497024653938370055035972339916800 '
        '3319904813130371492518305303772731725901963221095873210340048896 '
        '331638174811091740347115522223995404947111594925110585946931200 '
        '386363546767861101501344753090369545903822643059883231762939904 '
        '55952796334861328578657288637618615501840861285241755165286400 '
        '58993586569608936276190821029881050289049707383311518407819264 '
        '32551646814943690431250610264528047351227668501342857109446656'),
    29: ('2 3 5 7 13 17 19 23 29 31 37',
        '12350084735642851067993914859348749190509227265472022582978182076860203008 '
        '30674713643214437038756034349770990545546745498779107336809072477093756928 '
        '1499000387547557565187258187299978956333848249547403265925000000000000000 '
        '127649626715321021614003575841853741302732417644077293700657648635740160 '
        '2303709037283797373973604173647092034493397669523809048313562808467456 '
        '2138053350785394739988986928786658044560385249117030689315680919486464 '
        '951445634338275726025786714299185447655087636742886570225634285977600 '
        '782231012637367581497363909051192726457039319384127681153707087233024 '
        '313632157377249681627768675414129633861324545464743435852900264345600 '
        '52734144355897879222436916674904871918161986691820046657301118976000 '
        '13271208236533211044056989026578499181533409217602901768649294200832'),
    31: ('2 3 7 11 13 17 19 23 29 31 37 41 43',
        '5277355872393159411338930466020720111639815441556817265012712381778341319646951740445635213105561600 '
        '1362191382755951661410676420039779973458402530917398055790132673577887601075330935598255146948296704 '
        '10880293410314850219268841220536985512836177458859107788344092010122114288753171233190649875562496 '
        '2251477202636862581868434191940049385097163309395488406323712471842349378783985152498642878464000 '
        '279641521209618886866569564136864803126810350861085675748720657625546389466037241826912238632960 '
        '264330429813548597242050795186593683833392439894427877252795140812544403412375324340297597059072 '
        '113678639224764046807365477118253628998273863112717311085757039780108333949264703046335216877568 '
        '21427354175238182426580163333426836475202393809663774891850718351495926229875084939181114949632 '
        '6452554110741627771388762475666262809178551692649728057242519325421443594128791950037166194688 '
        '4544265842567556308706623374084316817152133934697484837959526064556136325365113627989545943040 '
        '1027337006055336321243681938542681672042529414416594592624044471478116274903717831103014567936 '
        '636921864672244939015959359755655780923673734364502905118997057137593400112971826419891634176 '
        '1979966390121406150181400585942940871765352389198485423558282561507897892251964975102226399232'),
    33: ('2 5 7 11 13 17 23 29 31 37 41 43 47 53 59',
        '32803129141072579223318067393204223905943328793088759499487536777528177424615720342565185124555269458824936492416340005437230493509103910912 '
        '73260652772010405413987955699083647547146333065685567071792665340538084271479679957351757570876629187714719250500205038750000000000000000 '
        '17901855718950489270821728551115840297494681853064949548302850547389951137621976506098379010638762957095239783726618518295516829024780288 '
        '2873740351280018820586169432109851641694902056963076632186296420685711155744666357275384626457186280537249818216869318799996097117814784 '
        '2349708630317139512879432902472713937854156260956872734074570893072132221251487887804016672606863701455941511957128435003308891220803584 '
        '860956251089850598439908582972301733616449168023202451248076385084374983897104894391386188305662035279169445092678701594932004223188992 '
        '35068577736216007265006490474393084673783539394995641973696762228420680014025779725892204479369521272198340552337677999053513002582016 '
        '24426215991488912761289156225801654105915137692251366247981224377324683616355811490338333183696755954939965590413171795456122571653120 '
        '35547792516104732133715975732291408433247235956720491477126755157560886970434585710020417949318091619254628784829604851194329096781824 '
        '589808233598323273280466734860270542158513896042778033316475188994028842814952355984168996019234943266366615691588033672232921202688 '
        '2132401091444529660267332789521167033157101956872236398614378313618340106039540117276380224113087412819228897705476609005727467962368 '
        '2854147622117762921942742698654876713262596316086671958655325730167234947278810934098209895628974051419069199263370015006581520859136 '
        '217860336912119795449958243568791799364882511097824158325137420779879520182193481053587801311321379607397620042406036167252852080640 '
        '1575624756591211860072230704207273219946789982371615494752730751618508847902465174593013260580424164699996094938426074444120384405504 '
        '482862923712638259156855683792475190541150594859312288316814078137566373427547910222204774794610590668589516084246695901911255613440'),
}

# Earlier independent, small-support solutions and the additional example.
BENCHMARKS = {
    'original-17': (17, [2, 3, 11],
                    [61698211840, 21101849055, 19487171]),
    'original-19': (19, [2, 3, 5, 11],
                    [723014123520, 104675276565, 9437500000, 214358881]),
    'original-21': (21, [2, 3, 5, 11, 13],
                    [194734743336517632, 30301017124018320,
                     2933578466796875, 61834820248784, 1622488404069]),
    'shifted-17': (17, [7, 11, 13],
                   [3057068752319198855, 52835608551768966,
                    93095697106496110]),
}


def convolve(a, b, n):
    """Truncated convolution over exact integers."""
    z = [0] * (n + 1)
    for i, ai in enumerate(a[:n + 1]):
        if ai:
            for j, bj in enumerate(b[:n + 1 - i]):
                if bj:
                    z[i + j] += ai * bj
    return z


def series_power(base, exponent, limit):
    result = [1] + [0] * limit
    while exponent:
        if exponent & 1:
            result = convolve(result, base, limit)
        exponent >>= 1
        if exponent:
            base = convolve(base, base, limit)
    return result


def divisor_power_series(limit, exponent):
    series = [0] * (limit + 1)
    for d in range(1, limit + 1):
        d_power = d ** exponent
        for n in range(d, limit + 1, d):
            series[n] += d_power
    return series


@lru_cache(maxsize=8)
def generators(limit):
    """Return the exact Fourier series E4, E6, Delta^2 through q^limit."""
    if limit < 2:
        raise ValueError('prime cutoff must be >= 2')
    s3 = divisor_power_series(limit, 3)
    s5 = divisor_power_series(limit, 5)
    e4 = [1] + [240 * x for x in s3[1:]]
    e6 = [1] + [-504 * x for x in s5[1:]]
    delta = [0, 1] + [0] * (limit - 1)
    for m in range(1, limit):
        factor = [0] * (limit + 1)
        for k in range(min(24, limit // m) + 1):
            factor[m * k] = (-1) ** k * math.comb(24, k)
        delta = convolve(delta, factor, limit)
    return e4, e6, convolve(delta, delta, limit)


@lru_cache(maxsize=512)
def coefficients(e4_exponent, e6_exponent, limit):
    e4, e6, delta2 = generators(limit)
    return convolve(convolve(delta2, series_power(e4, e4_exponent, limit), limit),
                    series_power(e6, e6_exponent, limit), limit)


def degree_rows(j):
    """(j, a, b) basis identifiers for j-th spherical harmonic moments."""
    if j < 12 or j % 2:
        return []
    w = j - 12
    return [(j, (w - 6 * b) // 4, b)
            for b in range(w // 6 + 1) if (w - 6 * b) % 4 == 0]


def rows_through(t):
    return [row for j in range(12, t + 1, 2) for row in degree_rows(j)]


def first_omitted_degree(t):
    j = t + 1
    if j % 2:
        j += 1
    while not degree_rows(j):
        j += 2
    return j


def is_prime(n):
    if not isinstance(n, int) or isinstance(n, bool) or n < 2:
        return False
    if n % 2 == 0:
        return n == 2
    return all(n % d for d in range(3, math.isqrt(n) + 1, 2))


def primes_through(limit):
    if limit < 2:
        return []
    sieve = bytearray(b'\x01') * (limit + 1)
    sieve[:2] = b'\x00\x00'
    for p in range(2, math.isqrt(limit) + 1):
        if sieve[p]:
            sieve[p * p:limit + 1:p] = b'\x00' * ((limit - p * p) // p + 1)
    return [p for p in range(2, limit + 1) if sieve[p]]


def spherical_moment(row, primes, weights, limit):
    j, a, b = row
    f = coefficients(a, b, limit)
    return sum((Fraction(w) * Fraction(f[p], (2 * p) ** (j // 2))
                for p, w in zip(primes, weights)), Fraction(0))


def parse_certificate(data):
    """Accept Paper II JSON or the compact {t,primes,weights} schema."""
    if not isinstance(data, dict):
        raise ValueError('certificate JSON must be an object')
    t = data.get('strength_at_least', data.get('t'))
    primes = data.get('prime_shells', data.get('primes'))
    weights = data.get('integer_per_point_weights', data.get('weights'))
    if type(t) is not int or t < 1:
        raise ValueError('strength must be a positive integer')
    if not isinstance(primes, list) or not primes:
        raise ValueError('a nonempty prime_shells/primes array is required')
    if not isinstance(weights, list) or len(primes) != len(weights):
        raise ValueError('weights array must be the same length as primes')
    if any(type(p) is not int or not is_prime(p) for p in primes):
        raise ValueError('shell indices must be prime integers')
    if len(set(primes)) != len(primes):
        raise ValueError('shell indices must be distinct')
    # A float is exact as a *binary* Fraction, but not necessarily the
    # rational number intended by a certificate author: e.g. Fraction(0.1)
    # is not 1/10. Boolean values are also not legitimate integer weights.
    # Fraction inputs are retained for callers using the Python API.
    if any(type(x) not in (int, str, Fraction) for x in weights):
        raise ValueError('weights must be exact integers or rational strings; '
                         'floating-point and boolean values are not accepted')
    try:
        w = [Fraction(x) for x in weights]
    except (ValueError, TypeError, ZeroDivisionError) as exc:
        raise ValueError('weights must be exact integers or rational strings') from exc
    if any(x <= 0 for x in w):
        raise ValueError('all per-point weights must be STRICTLY positive')
    return t, primes, w


def verify_data(data, *, inspect_omitted=True):
    """Recompute all ambient modular moments, ignoring claimed certified flags."""
    t, primes, weights = parse_certificate(data)
    limit = max(primes)
    rows = rows_through(t)
    first_failure = None
    for row in rows:
        residual = spherical_moment(row, primes, weights, limit)
        if residual:
            first_failure = {'degree': row[0], 'E4': row[1], 'E6': row[2],
                             'residual': str(residual)}
            break
    omitted_degree = first_omitted_degree(t) if inspect_omitted else None
    omitted_witness = None
    if inspect_omitted:
        for row in degree_rows(omitted_degree):
            residual = spherical_moment(row, primes, weights, limit)
            if residual:
                omitted_witness = {'degree': row[0], 'E4': row[1],
                                   'E6': row[2], 'residual': str(residual)}
                break
    geometric_exact_strength = (omitted_degree - 1
                                if omitted_witness and omitted_degree <= 172
                                and first_failure is None else None)
    result = {
        # 'verified' is a finite moment-and-integrity verdict, not a proof of
        # the separate automorphic prime cutoff or of Paper I surjectivity.
        'verified': first_failure is None,
        'verification_scope': 'finite exact modular moments and optional SHA-256',
        'strength_at_least': t,
        'prime_shells': primes,
        'shell_count': len(primes),
        'modular_rows_checked': len(rows),
        'imposed_moment_failure': first_failure,
        'first_omitted_ambient_degree': omitted_degree,
        'first_omitted_ambient_witness': omitted_witness,
        'exact_geometric_strength_using_Paper_I': geometric_exact_strength,
    }
    if 'sha256_without_hash_field' in data:
        claimed = data['sha256_without_hash_field']
        unhashed = dict(data)
        unhashed.pop('sha256_without_hash_field')
        encoded = json.dumps(unhashed, sort_keys=True, separators=(',', ':')).encode()
        result['archive_sha256_matches'] = (
            claimed == hashlib.sha256(encoded).hexdigest())
        if not result['archive_sha256_matches']:
            result['verified'] = False
    return result


def gaussian(A, rhs):
    """Exact square solver; returns None when singular."""
    n = len(rhs)
    a = [[Fraction(x) for x in row] + [Fraction(rhs[i])]
         for i, row in enumerate(A)]
    for col in range(n):
        pivot = next((i for i in range(col, n) if a[i][col]), None)
        if pivot is None:
            return None
        a[col], a[pivot] = a[pivot], a[col]
        q = a[col][col]
        a[col][col:] = [x / q for x in a[col][col:]]
        for i in range(col + 1, n):
            factor = a[i][col]
            if factor:
                a[i][col:] = [x - factor * y
                              for x, y in zip(a[i][col:], a[col][col:])]
    result = [Fraction(0)] * n
    for i in range(n - 1, -1, -1):
        result[i] = a[i][n] - sum(a[i][j] * result[j]
                                   for j in range(i + 1, n))
    return result


def primitive_integers(values):
    den = math.lcm(*(v.denominator for v in values))
    integers = [int(v * den) for v in values]
    gcd = math.gcd(*integers)
    return [n // gcd for n in integers]


def rational_rank(mat):
    if not mat:
        return 0
    a = [[Fraction(x) for x in row] for row in mat]
    m, n = len(a), len(a[0])
    rank = 0
    for j in range(n):
        pivot = next((i for i in range(rank, m) if a[i][j]), None)
        if pivot is None:
            continue
        a[rank], a[pivot] = a[pivot], a[rank]
        q = a[rank][j]
        a[rank][j:] = [x / q for x in a[rank][j:]]
        for i in range(rank + 1, m):
            if a[i][j]:
                factor = a[i][j]
                a[i][j:] = [x - factor * y
                            for x, y in zip(a[i][j:], a[rank][j:])]
        rank += 1
        if rank == m:
            return rank
    return rank


def all_exact_vertices(B, max_bases):
    """Enumerate every nonnegative basic vertex of Bv=0, sum(v)=1."""
    r, m = len(B), len(B[0])
    total = math.comb(m, r + 1)
    if total > max_bases:
        raise RuntimeError(
            'This standard-library EXACT VERTEX backend needs '
            f'{total:,} bases (> --max-bases {max_bases:,}). '
            'The general theorem is not a practical enumeration algorithm; '
            'use a stronger certified rational LP backend for this instance.')
    vertices = []
    for subset in itertools.combinations(range(m), r + 1):
        matrix = [[B[i][p] for p in subset] for i in range(r)]
        matrix.append([1] * (r + 1))
        v = gaussian(matrix, [0] * r + [1])
        if v is None or any(x < 0 for x in v):
            continue
        z = primitive_integers(v)
        w = [0] * m
        for p, zz in zip(subset, z):
            w[p] = zz
        vertices.append(w)
    return vertices, total


def vertex_cover(active, vertices):
    allowed = set(active)
    good = [v for v in vertices
            if all(not v[i] or i in allowed for i in range(len(v)))]
    covered = {i for v in good for i in active if v[i] > 0}
    return covered == allowed, good


def greedy_prune(B, vertices):
    """Remove unneeded columns without losing a strictly positive kernel."""
    m, r = len(B[0]), len(B)
    active = list(range(m))
    ok, _ = vertex_cover(active, vertices)
    if not ok or rational_rank(B) != r:
        raise ValueError('Prefix does not have a full-dimensional positive kernel')
    for idx in list(active):
        trial = [i for i in active if i != idx]
        if len(trial) < r + 1:
            continue
        feasible, _ = vertex_cover(trial, vertices)
        if feasible and rational_rank([[row[i] for i in trial] for row in B]) == r:
            active = trial
    feasible, usable = vertex_cover(active, vertices)
    if not feasible or len(active) > 2 * r:
        raise AssertionError('Pruning failed to produce the stated 2r support')
    selected = [next(v for v in usable if v[i] > 0) for i in active]
    integers = [sum(v[i] for v in selected) for i in active]
    common = math.gcd(*integers)
    integers = [x // common for x in integers]
    assert all(x > 0 for x in integers)
    assert all(sum(B[j][p] * integers[k] for k, p in enumerate(active)) == 0
               for j in range(r))
    return active, integers


def rational_null_vector(rows):
    """Nonzero rational null vector, or None for independent columns."""
    if not rows or not rows[0]:
        return None
    m, n = len(rows), len(rows[0])
    a = [[Fraction(x) for x in row] for row in rows]
    pivots = []
    pivot_row = 0
    for col in range(n):
        pivot = next((i for i in range(pivot_row, m) if a[i][col]), None)
        if pivot is None:
            continue
        a[pivot_row], a[pivot] = a[pivot], a[pivot_row]
        coeff = a[pivot_row][col]
        a[pivot_row] = [x / coeff for x in a[pivot_row]]
        for i in range(m):
            if i != pivot_row and a[i][col]:
                factor = a[i][col]
                a[i] = [x - factor * y for x, y in zip(a[i], a[pivot_row])]
        pivots.append(col)
        pivot_row += 1
        if pivot_row == m:
            break
    free = next((j for j in range(n) if j not in pivots), None)
    if free is None:
        return None
    d = [Fraction(0)] * n
    d[free] = Fraction(1)
    for i, col in enumerate(pivots):
        d[col] = -a[i][free]
    assert all(sum(Fraction(x) * y for x, y in zip(row, d)) == 0
               for row in rows)
    return d


def positive_witness_from_vertices(vertices, count):
    """Construct an integral positive kernel vector covering the prefix."""
    active = list(range(count))
    feasible, usable = vertex_cover(active, vertices)
    if not feasible:
        raise ValueError('Prefix has no strictly positive kernel witness')
    chosen = [next(v for v in usable if v[i] > 0) for i in active]
    v = [sum(z[i] for z in chosen) for i in active]
    assert all(x > 0 for x in v)
    return v


def caratheodory_purify(B, witness):
    """Exact elimination until augmented columns are independent (a vertex).

    B may be rank-deficient. The final support may have < r+1 columns.
    """
    if not B or len(witness) != len(B[0]):
        raise ValueError('Invalid moment matrix or witness length')
    active = [i for i, w in enumerate(witness) if w > 0]
    if not active or any(x < 0 for x in witness):
        raise ValueError('Witness must be nonnegative and nonzero')
    if any(sum(Fraction(B[j][i]) * Fraction(witness[i]) for i in range(len(witness)))
           for j in range(len(B))):
        raise ValueError('Initial witness does not annihilate moment matrix')
    mass = sum((Fraction(witness[i]) for i in active), Fraction(0))
    values = [Fraction(witness[i]) / mass for i in active]
    steps = 0
    while True:
        aug = [[B[j][i] for i in active] for j in range(len(B))]
        aug.append([1] * len(active))
        d = rational_null_vector(aug)
        if d is None:
            break
        neg = [i for i, x in enumerate(d) if x < 0]
        pos = [i for i, x in enumerate(d) if x > 0]
        if not neg or not pos:
            raise AssertionError('Null direction must have both signs')
        theta = min(values[i] / -d[i] for i in neg)
        updated = [values[i] + theta * d[i] for i in range(len(active))]
        retained = [(idx, val) for idx, val in zip(active, updated) if val]
        assert all(val > 0 for _, val in retained)
        active = [idx for idx, _ in retained]
        values = [val for _, val in retained]
        steps += 1
    assert len(active) <= len(B) + 1
    assert rational_null_vector([[B[j][i] for i in active] for j in range(len(B))]
                                + [[1] * len(active)]) is None
    weights = primitive_integers(values)
    assert all(w > 0 for w in weights)
    assert all(sum(B[j][idx] * w for idx, w in zip(active, weights)) == 0
               for j in range(len(B)))
    return active, weights, steps


def construct_certificate(t, cutoff, lower_prime=0, max_bases=100000,
                          full_dimensional=False):
    """Finite-prime exact construction. May fail even when an all-strength design exists."""
    if t < 1 or cutoff < 2 or lower_prime < 0:
        raise ValueError('strength >=1, cutoff >=2, lower_prime >=0 required')
    primes = [p for p in primes_through(cutoff) if p > lower_prime]
    if not primes:
        raise ValueError('No primes in the requested range')
    K = 2 * (t // 2)
    basis = rows_through(K)
    r = len(basis)
    if not r:
        result = {'strength_at_least': t, 'prime_shells': [primes[0]],
                  'integer_per_point_weights': [1], 'total_modular_constraints': 0,
                  'full_prefix_primes': primes, 'method': 'single shell (11-design)'}
    else:
        if len(primes) < r + 1:
            raise ValueError(f'Need at least {r + 1} primes for full-dimensional '
                             f'construction; received {len(primes)}')
        B = [[coefficients(a, b, cutoff)[p] * (2 * p) ** ((K - j) // 2)
              for p in primes] for j, a, b in basis]
        vertices, examined = all_exact_vertices(B, max_bases)
        if full_dimensional:
            active, z = greedy_prune(B, vertices)
            steps = None
        else:
            witness = positive_witness_from_vertices(vertices, len(primes))
            active, z, steps = caratheodory_purify(B, witness)
        support = [primes[i] for i in active]
        weights = [z[i] * (2 * p) ** (K // 2) for i, p in enumerate(support)]
        result = {
            'strength_at_least': t,
            'full_prefix_primes': primes,
            'prime_shells': support,
            'integer_per_point_weights': weights,
            'integer_scaled_kernel': z,
            'rows': [{'degree': j, 'E4': a, 'E6': b} for j, a, b in basis],
            'total_modular_constraints': r,
            'shell_cap_r_plus_1': r + 1,
            'full_dimensional_shell_cap_2r': 2 * r,
            'basis_subsets_examined': examined,
            'nonnegative_vertices_found': len(vertices),
            'method': ('exact rational vertex enumeration and full-dimensional greedy pruning'
                       if full_dimensional else
                       'exact rational vertex enumeration plus Caratheodory purification'),
            'certificate_type': ('full_dimensional' if full_dimensional
                                 else 'sparse_vertex'),
            'purification_steps': steps,
        }
    audit = verify_data(result)
    if not audit['verified']:
        raise AssertionError('Constructor produced a nonzero imposed moment')
    result['first_omitted_degree'] = audit['first_omitted_ambient_degree']
    result['first_omitted_ambient_witness'] = audit['first_omitted_ambient_witness']
    result['exact_geometric_strength_using_Paper_I'] = (
        audit['exact_geometric_strength_using_Paper_I'])
    result['certified'] = True
    result['certificate_scope'] = 'finite exact modular moments; analytic cutoff not tested'
    payload = json.dumps(result, sort_keys=True, separators=(',', ':')).encode()
    result['sha256_without_hash_field'] = hashlib.sha256(payload).hexdigest()
    return result


def independent_series_test(limit=59):
    """Cross-check Delta^2 against q^2 prod(1-q^m)^48 and Eisenstein sums."""
    e4, e6, delta2 = generators(limit)
    alternative = [0, 0, 1] + [0] * (limit - 2)
    for m in range(1, limit - 1):
        factor = [0] * (limit + 1)
        for k in range(min(48, limit // m) + 1):
            factor[m * k] = (-1) ** k * math.comb(48, k)
        alternative = convolve(alternative, factor, limit)
    assert alternative == delta2, 'independent Delta^2 series disagreement'
    for n in range(1, limit + 1):
        divs = [d for d in range(1, n + 1) if n % d == 0]
        assert e4[n] == 240 * sum(d ** 3 for d in divs)
        assert e6[n] == -504 * sum(d ** 5 for d in divs)


def certificate_validation_test():
    """Ensure non-exact JSON values and altered certificates are rejected."""
    basic = {'t': 11, 'primes': [2], 'weights': [1]}
    assert verify_data(basic, inspect_omitted=False)['verified']
    for bad in [True, False, 0.1, 1.5, 0, -1, 'bad', '1/0']:
        altered = dict(basic, weights=[bad])
        try:
            verify_data(altered, inspect_omitted=False)
        except ValueError:
            pass
        else:
            raise AssertionError(f'invalid weight was accepted: {bad!r}')
    assert parse_certificate(dict(basic, weights=['1/2']))[2] == [Fraction(1, 2)]
    assert parse_certificate(dict(basic, weights=[Fraction(3, 7)]))[2] == [Fraction(3, 7)]
    original = {'strength_at_least': 17, 'prime_shells': [2, 3, 11],
                'integer_per_point_weights': [61698211840, 21101849055, 19487171]}
    assert verify_data(original, inspect_omitted=False)['verified']
    tampered = dict(original, integer_per_point_weights=[61698211841, 21101849055, 19487171])
    assert not verify_data(tampered, inspect_omitted=False)['verified']
    hashed = dict(original)
    digest = json.dumps(hashed, sort_keys=True, separators=(',', ':')).encode()
    hashed['sha256_without_hash_field'] = hashlib.sha256(digest).hexdigest()
    assert verify_data(hashed, inspect_omitted=False)['verified']
    hashed['sha256_without_hash_field'] = '0' * 64
    assert not verify_data(hashed, inspect_omitted=False)['verified']


def caratheodory_regression_test():
    """Exact vertex/rank-deficiency checks and construction consistency."""
    # A zero column permits a rank-deficient singleton vertex with k < r+1.
    B = [[1, -1, 0], [0, 0, 0]]
    active, weights, _ = caratheodory_purify(B, [1, 1, 2])
    assert all(sum(B[j][idx] * w for idx, w in zip(active, weights)) == 0
               for j in range(2))
    assert len(active) <= 3
    assert rational_null_vector([[B[j][i] for i in active] for j in range(2)]
                                + [[1] * len(active)]) is None
    active, weights, _ = caratheodory_purify(B, [0, 0, 1])
    assert active == [2] and weights == [1]
    # This test includes an actual nontrivial rank-2 Leech moment matrix.
    for t, cutoff in [(17, 11), (19, 11)]:
        cert = construct_certificate(t, cutoff)
        assert verify_data(cert)['verified']
        assert len(cert['prime_shells']) <= len(rows_through(t)) + 1
        assert cert['certificate_type'] == 'sparse_vertex'
        full = construct_certificate(t, cutoff, full_dimensional=True)
        assert verify_data(full)['verified']
        assert len(full['prime_shells']) <= 2 * len(rows_through(t))


def bundled_entries():
    for t, (ps, ws) in sorted(BUNDLED_CERTIFICATES.items()):
        yield f'archived-{t}', {'strength_at_least': t,
                                'prime_shells': [int(x) for x in ps.split()],
                                'integer_per_point_weights': [int(x) for x in ws.split()]}
    for name, (t, primes, weights) in BENCHMARKS.items():
        yield name, {'strength_at_least': t, 'prime_shells': primes,
                     'integer_per_point_weights': weights}


def print_audit(label, result):
    witness = result['first_omitted_ambient_witness']
    exact = result['exact_geometric_strength_using_Paper_I']
    verdict = 'PASS' if result['verified'] else 'FAIL'
    print(f'{verdict} {label}: strength >= {result["strength_at_least"]}; '
          f'{result["shell_count"]} shells; '
          f'{result["modular_rows_checked"]} exact conditions')
    if result['imposed_moment_failure']:
        print('  First imposed failure:', result['imposed_moment_failure'])
    if witness:
        print('  First omitted ambient witness:', witness)
    if exact is not None:
        print(f'  Exact geometric strength {exact} USING Paper I surjectivity')
    elif witness:
        print('  Ambient witness does NOT by itself certify exact geometric strength')
    if result.get('archive_sha256_matches') is False:
        print('  ERROR: certificate archive SHA-256 mismatch')


def cmd_examples(_):
    for name, data in bundled_entries():
        t, ps, ws = parse_certificate(data)
        print(f'{name:15s} t={t:2d}, shells={len(ps):2d}, '
              f'largest prime={max(ps):2d}, '
              f'max integer weight bits={max(w.numerator.bit_length() for w in ws)}')
    return 0


def cmd_test(args):
    independent_series_test()
    certificate_validation_test()
    caratheodory_regression_test()
    count = 0
    for name, data in bundled_entries():
        result = verify_data(data)
        print_audit(name, result)
        if not result['verified']:
            return 1
        if name in ('original-17', 'shifted-17'):
            expected = (Fraction(-8244600, 11) if name == 'original-17'
                        else Fraction(1781472164356692450, 143))
            if Fraction(result['first_omitted_ambient_witness']['residual']) != expected:
                raise AssertionError('Strength-17 omitted witness mismatch')
        count += 1
    if args.archive:
        files = sorted(Path(args.archive).glob('example_strength*.json'))
        if not files:
            raise ValueError('No example_strength*.json files in archive directory')
        for file in files:
            data = json.loads(file.read_text(encoding='utf-8'))
            result = verify_data(data)
            print_audit(str(file), result)
            if not result['verified']:
                return 1
            count += 1
    print(f'ALL {count} CERTIFICATES PASSED; independent q-series cross-check passed')
    print('Exact-input, tamper-detection, checksum and vertex-purification regression checks passed')
    print('SCOPE: finite rational moment certificates only; analytic cutoff theorem NOT tested')
    return 0


def cmd_verify(args):
    paths = ([Path(args.certificate)] if args.certificate
             else sorted(Path(args.archive).glob('example_strength*.json')))
    if not paths:
        raise ValueError('No matching certificate files found')
    result_code = 0
    for path in paths:
        data = json.loads(path.read_text(encoding='utf-8'))
        result = verify_data(data, inspect_omitted=not args.no_omitted)
        print_audit(path.name, result)
        if not result['verified']:
            result_code = 1
    print('SCOPE: finite rational moment certificates only; analytic cutoff theorem NOT tested')
    return result_code


def cmd_construct(args):
    data = construct_certificate(args.strength, args.prime_limit,
                                 args.lower_prime, args.max_bases,
                                 full_dimensional=args.full_dimensional)
    result = verify_data(data)
    print_audit('new construction', result)
    if args.out:
        args.out.write_text(json.dumps(data, indent=2) + '\n', encoding='utf-8')
        print('Wrote exact certificate:', args.out)
    else:
        print(json.dumps(data, indent=2))
    return 0


def main(argv=None):
    ap = argparse.ArgumentParser(description=__doc__,
                                 formatter_class=argparse.RawDescriptionHelpFormatter)
    sub = ap.add_subparsers(dest='command', required=True)
    examples = sub.add_parser('examples', help='list embedded exact certificates')
    examples.set_defaults(handler=cmd_examples)
    tests = sub.add_parser('test', help='verify all 13 built-in examples, optionally an archive')
    tests.add_argument('--archive', type=Path, help='also check external example_strength*.json')
    tests.set_defaults(handler=cmd_test)
    verify = sub.add_parser('verify', help='check a JSON certificate with independent exact moments')
    verify_group = verify.add_mutually_exclusive_group(required=True)
    verify_group.add_argument('certificate', type=Path, nargs='?', help='certificate JSON')
    verify_group.add_argument('--archive', type=Path, help='folder of example_strength*.json')
    verify.add_argument('--no-omitted', action='store_true', help='omit first-omitted-degree test')
    verify.set_defaults(handler=cmd_verify)
    make = sub.add_parser('construct', help='exact prefix search and <=r+1 vertex purification')
    make.add_argument('--strength', type=int, default=17)
    make.add_argument('--prime-limit', type=int, default=11)
    make.add_argument('--lower-prime', type=int, default=0)
    make.add_argument('--max-bases', type=int, default=100000)
    make.add_argument('--full-dimensional', action='store_true',
                      help='use legacy full-dimensional greedy mode (<=2r shells)')
    make.add_argument('--out', type=Path, help='write machine-readable JSON certificate')
    make.set_defaults(handler=cmd_construct)
    args = ap.parse_args(argv)
    try:
        return args.handler(args)
    except (ValueError, RuntimeError, OSError, AssertionError) as exc:
        print('ERROR:', exc, file=sys.stderr)
        return 2

if __name__ == '__main__':
    if 'ipykernel' in sys.modules:
        # Running inside Google Colab or Jupyter
        main(['test'])
    else:
        # Running from a normal terminal
        sys.exit(main())
