"""Kickoff 09. Generalization of ../kickoff08/curve.py; geometry only.

Run: ../.venv-knot12d-blind/bin/python curves.py
Reads only frozen local predictions and its own source. Exhaustive subsets;
exact ties in Z[z]/Phi_N; certified integer intervals for strict ordering.
All coefficients and interval operations are integers. Floats are display only.
"""
from collections import Counter
from datetime import datetime, timezone
from decimal import Decimal, localcontext
from fractions import Fraction
from functools import lru_cache
import hashlib
import itertools
import json
import math
import os
from pathlib import Path
import platform
import resource
import subprocess
import sys
import time

HERE = Path(__file__).resolve().parent
os.environ.setdefault('MPLCONFIGDIR', str(HERE / '.matplotlib-cache'))
COUNTS = (29, 25, 32, 30, 26, 27)
PARENT_SHA = '42a63b3a37523e32c83e7d1885693dc6a7e3dbd53ea5fef9698ccfb60038fba5'
Q = 10**100


def sha(path):
    return hashlib.sha256(Path(path).read_bytes()).hexdigest()


def ceildiv(a, b):
    return -((-a)//b)


def atan_inverse(q, terms=100):
    # Unchanged integer enclosure method from Kickoff 08.
    lo = hi = 0
    for k in range(terms):
        denominator = (2*k+1)*q**(2*k+1)
        low, high = Q//denominator, ceildiv(Q, denominator)
        if k % 2:
            lo -= high
            hi -= low
        else:
            lo += low
            hi += high
    tail = ceildiv(Q, (2*terms+1)*q**(2*terms+1))
    return lo-tail, hi+tail


def cosine_bounds(k, N, pi_bounds):
    # Generalized from cosine_bounds in curve.py: every modulus is now N.
    k = min(k % N, (-k) % N)
    if k == 0:
        return Q, Q
    xl = 2*k*pi_bounds[0]//N
    xh = ceildiv(2*k*pi_bounds[1], N)
    assert 0 < xl <= xh < 4*Q
    x2l, x2h = xl*xl//Q, ceildiv(xh*xh, Q)
    tl = th = low = high = Q
    for n in range(1, 101):
        denominator = Q*(2*n-1)*(2*n)
        tl, th = tl*x2l//denominator, ceildiv(th*x2h, denominator)
        if n % 2:
            low -= th
            high -= tl
        else:
            low += tl
            high += th
    remainder = ceildiv(Q*4**202, math.factorial(202))
    return low-remainder, high+remainder


def trim(p):
    while len(p) > 1 and p[-1] == 0:
        p.pop()
    return p


def divmod_poly(a, b):
    a = trim(list(a))
    assert b[-1] == 1
    q = [0]*max(1, len(a)-len(b)+1)
    while len(a) >= len(b) and any(a):
        shift, c = len(a)-len(b), a[-1]
        q[shift] = c
        for j, v in enumerate(b):
            a[j+shift] -= c*v
        trim(a)
    return trim(q), a


@lru_cache(None)
def cyclotomic(N):
    p = [-1]+[0]*(N-1)+[1]
    for d in range(1, N):
        if N % d == 0:
            p, remainder = divmod_poly(p, cyclotomic(d))
            assert not any(remainder)
    return tuple(p)


def monomial(k, N, phi):
    _, p = divmod_poly([0]*(k % N)+[1], phi)
    return tuple(p+[0]*(len(phi)-1-len(p)))


def gap_atom(k, N, phi):
    a, b = monomial(k, N, phi), monomial(-k, N, phi)
    return tuple((2 if i == 0 else 0)-x-y for i, (x, y) in enumerate(zip(a, b)))


def compare(a, b):
    if a[0] == b[0]:
        return 0
    if a[2] < b[1]:
        return -1
    if b[2] < a[1]:
        return 1
    raise ArithmeticError('Unequal cyclotomic values overlap; increase interval precision')


def exact_row(row):
    return (tuple(row['exact_gap']['numerator_coefficients_ascending']),
            int(row['gap_interval_scaled']['lower']), int(row['gap_interval_scaled']['upper']))


def compare_rows(a, b):
    x, y = exact_row(a), exact_row(b)
    return compare((tuple(v*b['L'] for v in x[0]), x[1]*b['L'], x[2]*b['L']),
                   (tuple(v*a['L'] for v in y[0]), y[1]*a['L'], y[2]*a['L']))


def rational(row, a, b=1):
    p = row['exact_gap']['numerator_coefficients_ascending']
    return not any(p[1:]) and p[0]*b == a*row['L']


def mix(ms, N):
    c = Counter(math.gcd(m, N) for m in ms)
    return {str(d): c[d] for d in sorted(c)}


def polynomial_text(p):
    terms = []
    for j, c in enumerate(p):
        if not c:
            continue
        x = '' if j == 0 else ('z' if j == 1 else f'z^{j}')
        term = str(abs(c)) if not x else ('' if abs(c) == 1 else str(abs(c))+'*')+x
        terms.append(('-' if c < 0 else '+' if terms else '')+term)
    return ''.join(terms) or '0'


def short_quadratic(p, phi, L, lower, upper):
    """Recognize quadratic exact values by squaring in the cyclotomic field."""
    square = [0]*(2*len(p)-1)
    for i,a in enumerate(p):
        for j,b in enumerate(p):
            square[i+j] += a*b
    _, square = divmod_poly(square,phi)
    square += [0]*(len(p)-len(square))
    j = next(i for i in range(1,len(p)) if p[i])
    B = Fraction(square[j],p[j])
    if any(square[i] != B*p[i] for i in range(1,len(p))):
        return None
    A = square[0]-B*p[0]
    discriminant = B*B+4*A
    assert discriminant > 0
    if 2*lower*B.denominator > B.numerator*Q:
        sign = '+'
    else:
        assert 2*upper*B.denominator < B.numerator*Q
        sign = '-'
    return f'({B}{sign}sqrt({discriminant}))/{2*L}'


def validate_exhaustive(N, rows, atoms, lows, highs):
    """Second exhaustive pass, direct combinations and direct sums, no Gray state.

    For a losing set, a single station upper bound below the optimum suffices.
    Every remaining set is compared exactly at every potentially minimal step.
    """
    begin = time.monotonic_ns()
    K, degree = N//2, len(atoms[0][0])
    checked = 0
    for row in rows:
        winner = exact_row(row)
        discovered = set()
        for ms in itertools.combinations(range(1,K+1),row['L']):
            checked += 1
            intervals = []
            for s in range(K):
                hi = sum(highs[m-1][s] for m in ms)
                if hi < winner[1]:
                    break
                intervals.append((sum(lows[m-1][s] for m in ms),hi))
            else:
                minhi = min(v[1] for v in intervals)
                minimum = None
                for s,(lo,hi) in enumerate(intervals):
                    if lo <= minhi:
                        p = tuple(sum(atoms[m-1][s][j] for m in ms) for j in range(degree))
                        val = (p,lo,hi)
                        if minimum is None or compare(val,minimum)<0:
                            minimum = val
                order = compare(minimum,winner)
                assert order <= 0, (N,row['L'],ms,'better set missed')
                if order == 0:
                    discovered.add(ms)
        assert discovered == {tuple(t['multipliers']) for t in row['tied_sets']}
    assert checked == (1 << K)-1
    return {'method':'Independent lexicographic combinations with direct integer sums; all optima and every tied set match',
            'subsets_checked':checked,'wall_seconds':(time.monotonic_ns()-begin)/1e9}


def geometry(N, pi_bounds):
    begin = time.monotonic_ns()
    K = N//2
    phi = cyclotomic(N)
    degree = len(phi)-1
    assert degree == sum(math.gcd(i, N) == 1 for i in range(1, N+1))
    cosines = [cosine_bounds(k, N, pi_bounds) for k in range(N)]
    atoms = [[gap_atom(m*s, N, phi) for s in range(1, K+1)] for m in range(1, K+1)]
    lows = [[2*Q-2*cosines[m*s % N][1] for s in range(1, K+1)] for m in range(1, K+1)]
    highs = [[2*Q-2*cosines[m*s % N][0] for s in range(1, K+1)] for m in range(1, K+1)]
    best = [None]*(K+1)
    tied = [[] for _ in range(K+1)]
    seen = [0]*(K+1)
    lo = [0]*K
    hi = [0]*K
    previous = 0
    # Gray traversal visits each nonempty subset once, updating integer bounds
    # in O(K). Algebraic polynomials are constructed only for contenders.
    for ordinal in range(1, 1 << K):
        bits = ordinal ^ (ordinal >> 1)
        changed = bits ^ previous
        j = changed.bit_length()-1
        sign = 1 if bits & changed else -1
        for s in range(K):
            lo[s] += sign*(lows[j][s] if sign == 1 else highs[j][s])
            hi[s] += sign*(highs[j][s] if sign == 1 else lows[j][s])
        previous = bits
        L = bits.bit_count()
        seen[L] += 1
        minlo, minhi = min(lo), min(hi)
        if best[L] is not None and minhi < best[L][1]:
            continue
        ms = tuple(m+1 for m in range(K) if bits & (1 << m))
        candidates = [s for s in range(K) if lo[s] <= minhi]
        values = []
        for s in candidates:
            p = tuple(sum(atoms[m-1][s][j] for m in ms) for j in range(degree))
            values.append((p, lo[s], hi[s]))
        value = values[0]
        # All unresolved station comparisons must be algebraic equalities.
        for other in values[1:]:
            assert compare(value, other) == 0
        order = 1 if best[L] is None else compare(value, best[L])
        if order > 0:
            best[L], tied[L] = value, [ms]
        elif order == 0:
            tied[L].append(ms)
    rows = []
    units = [u for u in range(1, N) if math.gcd(u, N) == 1]
    for L in range(1, K+1):
        assert seen[L] == math.comb(K, L)
        tied[L].sort()
        remaining, allsets = set(tied[L]), set(tied[L])
        orbits = []
        while remaining:
            seed = min(remaining)
            orbit = {tuple(sorted(min(m*u % N, (-m*u) % N) for m in seed)) for u in units}
            assert orbit <= allsets and orbit <= remaining
            remaining -= orbit
            assert all(mix(ms, N) == mix(seed, N) for ms in orbit)
            orbits.append({'representative': list(seed), 'size': len(orbit),
                           'class_mix': mix(seed, N), 'sets': [list(ms) for ms in sorted(orbit)]})
        p, lower, upper = best[L]
        # Recompute tight bounds for the selected exact value, independent of
        # accumulated Gray traversal interval width, and verify every station.
        rep = tied[L][0]
        vals = []
        for s in range(K):
            poly = tuple(sum(atoms[m-1][s][j] for m in rep) for j in range(degree))
            vals.append((poly, sum(lows[m-1][s] for m in rep), sum(highs[m-1][s] for m in rep)))
        minsteps = []
        for s, val in enumerate(vals, 1):
            order = compare(val, best[L])
            assert order >= 0
            if order == 0:
                lower, upper = val[1], val[2]
                minsteps.extend([s, N-s])
        with localcontext() as ctx:
            ctx.prec = 90
            gap = Decimal(lower+upper)/Decimal(2*Q*L)
            r = (gap/2).sqrt()
        rat = not any(p[1:])
        formula = str(Fraction(p[0], L)) if rat else f'({polynomial_text(p)})/{L}'
        short_form = None if rat else short_quadratic(p,phi,L,lower,upper)
        patterns = Counter(tuple(sorted(mix(ms, N).items())) for ms in tied[L])
        row = {'L': L, 'dimension': 2*L+2, 'subsets_searched': seen[L],
               'gap': float(gap), 'gap_decimal': str(gap), 'r_star': float(r), 'r_star_decimal': str(r),
               'exact_gap': {'z_definition': f'exp(2*pi*i/{N})', 'minimal_polynomial_coefficients_ascending': list(phi),
                             'numerator_coefficients_ascending': list(p), 'denominator': L, 'formula': formula,
                             'short_closed_form':short_form},
               'gap_is_rational': rat, 'exact_r_star': 'sqrt(exact_gap/2)',
               'gap_interval_scaled': {'lower': str(lower), 'upper': str(upper), 'denominator': str(Q*L)},
               'ties': len(tied[L]), 'representative': list(rep), 'minimizing_station_steps': sorted(set(minsteps)),
               'tied_sets': [{'multipliers': list(ms), 'class_mix': mix(ms, N)} for ms in tied[L]],
               'class_mix_summary': [{'class_mix': dict(pattern), 'sets': count} for pattern, count in sorted(patterns.items())],
               'orbits': orbits}
        rows.append(row)
        print(f'N={N} L={L:2d} gap={gap:.12f} r={r:.12f} ties={len(tied[L])} orbits={len(orbits)}', flush=True)
    drops = [[a['L'], b['L']] for a, b in zip(rows, rows[1:]) if compare_rows(a, b) > 0]
    plateaus = [[a['L'], b['L']] for a, b in zip(rows, rows[1:]) if compare_rows(a, b) == 0]
    levels = [r['L'] for r in rows if rational(r, 2)]
    # Known complete-family identity, explicitly testing the even Nyquist case.
    for s, val in enumerate(vals, 1):
        expected = N if N % 2 == 0 and s % 2 == 0 else N+2 if N % 2 == 0 else N
        assert val[0] == (expected,)+(0,)*(degree-1)
    search_seconds = (time.monotonic_ns()-begin)/1e9
    verification = validate_exhaustive(N,rows,atoms,lows,highs)
    return {'N': N, 'L_max': K, 'subsets_searched': sum(seen), 'tie_method': 'exact cyclotomic equality',
            'cyclotomic_polynomial': polynomial_text(phi), 'rows': rows, 'decreases': drops,
            'adjacent_plateaus': plateaus, 'exact_r1_rows': levels,
            'simplex_ceiling': math.sqrt(N/(N-1)), 'simplex_ceiling_exact': f'sqrt({N}/{N-1})',
            'search_wall_seconds':search_seconds,'verification':verification,
            'wall_seconds': (time.monotonic_ns()-begin)/1e9}


def assess(c):
    N, rows = c['N'], c['rows']
    K = c['L_max']
    unitset = [m for m in range(1, K+1) if math.gcd(m, N) == 1]
    has = lambda L, ms: any(t['multipliers'] == ms for t in rows[L-1]['tied_sets'])
    multi = any(len(r['orbits']) > 1 for r in rows)
    level_predictions = {29: [], 25: [10], 32: [8,12,14,15,16], 30: [14,15], 26: [12,13], 27: [9,12]}
    adjacent_predictions = {29: [],25: [],32: [[14,15],[15,16]],30: [[14,15]],26: [[12,13]],27: []}
    specified_sets = {29: {},25: {10: unitset},32: {L: list(range(1,K+1)) if L==16 else [m for m in range(1,K+1) if math.gcd(m,N)<=d] for L,d in [(8,1),(12,2),(14,4),(15,8),(16,16)]},30: {14:list(range(1,15)),15:list(range(1,16))},26:{12:list(range(1,13)),13:list(range(1,14))},27:{9:unitset,12:[m for m in range(1,K+1) if math.gcd(m,N)<=3]}}[N]
    monotone = not c['decreases']
    M = monotone if N in (29,26) else not monotone
    for n, drop in [(25,[10,11]),(32,[8,9]),(27,[9,10])]:
        if N == n:
            M = M and drop in c['decreases']
    P = c['exact_r1_rows'] == level_predictions[N] and c['adjacent_plateaus'] == adjacent_predictions[N] and all(has(L, ms) for L,ms in specified_sets.items())
    T = rows[0]['ties'] == len(unitset) and rows[-1]['ties'] == 1
    T = T and (not multi if N in (29,26) else multi)
    if N != 29:
        T = T and all(rows[L-1]['ties']==1 for L in level_predictions[N])
    if N % 2:
        C = rational(rows[-1], 2*N, N-1) and all(compare_rows(r, rows[-1])<0 for r in rows[:-1])
    else:
        C = rational(rows[-1],2) and all(compare_rows(r,rows[-1])<=0 for r in rows) and len(rows[-1]['minimizing_station_steps']) < N-1
    return {f'{N}-{key}': 'HELD' if val else 'FAILED' for key,val in [('M',M),('P',P),('T',T),('C',C)]}


def plot(curves):
    import matplotlib
    matplotlib.use('Agg')
    import matplotlib.pyplot as plt
    fig, (ax, zoom) = plt.subplots(1,2,figsize=(14,6),width_ratios=[2,1],layout='constrained')
    colors = ['#006BA4','#FF800E','#ABABAB','#595959','#5F9ED1','#C85200']
    for c, color in zip(curves, colors):
        x = [r['L']/c['L_max'] for r in c['rows']]
        y = [r['r_star'] for r in c['rows']]
        for a in (ax, zoom):
            a.plot(x,y,'o-',ms=4,lw=1.4,color=color,label=f"N={c['N']}")
            a.axhline(c['simplex_ceiling'],color=color,ls=':',lw=0.9,alpha=0.8)
            level = [r for r in c['rows'] if r['L'] in c['exact_r1_rows']]
            a.scatter([r['L']/c['L_max'] for r in level],[r['r_star'] for r in level],s=85,facecolors='none',edgecolors=color,linewidths=1.4,zorder=5)
            for i,j in c['adjacent_plateaus']:
                a.plot(x[i-1:j],y[i-1:j],color=color,lw=4,alpha=0.65)
    for a in (ax,zoom):
        a.set_xlabel('Fraction of available circles, L / floor(N/2)')
        a.grid(alpha=.18)
        a.spines[['top','right']].set_visible(False)
    ax.set_ylabel('Optimal crowding threshold r*')
    ax.set_ylim(0,1.05)
    ax.legend(loc='lower right',ncol=2)
    zoom.set_xlim(.55,1.02)
    zoom.set_ylim(.94,1.025)
    zoom.set_title('Upper portion enlarged',fontsize=11)
    ax.set_title('Six exhaustive spacing curves',loc='left',fontweight='bold')
    fig.suptitle('Rings mark exact r*=1; thick segments mark adjacent plateaus; dotted lines are simplex ceilings',fontsize=10)
    fig.savefig(HERE/'curves.png',dpi=180)
    plt.close(fig)
    return matplotlib.__version__


def report(data):
    prose = {
        29: 'Every available circle is a unit, so gcd composition is identical for every size-L subset. Nevertheless the best threshold falls from 0.8703454266 at L=4 to 0.8688052438 at L=5. This directly defeats my monotonicity prediction and the explanation that dips require mixing divisor classes. Equal-radius normalization changes all circle weights when L changes, so adding a circle is not guaranteed to improve the minimum gap. The search selects one unit orbit at every L, with smaller orbits of size 7 at L=2 and 4 and size 2 at L=7. The full set is the simplex.',
        25: 'The circle kinds are units and multiples of 5. The winners mix those kinds at L=3 and 4, return to units alone at L=5 through 7, then mix again at L=8 and 9. All ten units uniquely reach r*=1. Adding either of the two remaining circles reduces the optimum to 0.9858537143; adding both produces the simplex. At L=8 and 9 there are two tied unit orbits even though the class mix is identical within each row. Thus a class mix does not uniquely specify the geometry.',
        32: 'The gcd classes form the chain 1, 2, 4, 8, 16. The unique best sets at r*=1 successively include all units, then all gcd-2 circles, then gcd-4 circles, then the gcd-8 circle, and finally the two-point multiplier 16. Those sizes are 8, 12, 14, 15 and 16. Partial additions produce dips at 8 to 9 and 12 to 13. At L=10 two quite different mixtures tie: eight units plus one gcd-2 and one gcd-8 circle, or five units plus two gcd-2, two gcd-4 and one gcd-8 circle. The terminal plateau ends at r*=1, below the simplex bound.',
        30: 'This count mixes seven gcd kinds, and units alone are not automatically the best ingredients. At L=2 both winning sets use one gcd-3 and one gcd-5 circle, with no unit circle. I missed the exact r*=1 optima at L=10 and 12: the former contains every representative not divisible by 3, and the latter every representative not divisible by 5. Both are unique. These join the predicted levels at 14 and 15. Distinct class mixtures tie at L=6, 8, 11 and 13, and at L=8 there are two separate orbits of size one. The extra levels and intervening dips are real, not numerical noise.',
        26: 'The ingredients are six units, six gcd-2 circles and the two-point multiplier 13. All six units uniquely win at L=6; adding 13 gives the unique L=7 winner and raises the threshold to 0.9636241117. The best L=8 mixture has four units and four gcd-2 circles, and its threshold falls to 0.9292820819. This defeats my monotonicity prediction. My one-orbit prediction also fails at L=5 and 9. The last two sizes give the predicted r*=1 plateau. In particular the unusual behavior is not restricted to prime powers.',
        27: 'This rerun independently enumerates the reference count in the generalized code, without loading its old results. The unique all-unit set at L=9 reaches r*=1, and adjoining all three gcd-3 circles returns to that level at L=12. The intervening values are lower. Earlier optima are not a simple process of filling one gcd class at a time: L=5 uses three units, one gcd-3 and one gcd-9 circle, while L=6 uses six units. Different class mixes tie at L=8 and 10. The full thirteen-circle set is the simplex. The kickoff had already disclosed the two exact level returns, so those successful predictions are not blind discoveries.'}
    lines = ['# Kickoff 09: six exact spacing curves','',
        'This is an exhaustive geometry calculation under the supplied equal-radius rule. No N=27 result file was read or imported. The N=27 facts already disclosed in the kickoff informed its frozen predictions. No dynamics were run.','',
        'All ties are exact polynomial equalities modulo a generated cyclotomic polynomial. Strict inequalities use outward-rounded integer intervals at scale 10^100. There was no float64 fallback. Decimal table entries are rounded displays. A second exhaustive pass using direct sums and lexicographic combinations, independent of the Gray traversal, verified every optimum and the complete tied-set lists.','',
        '“Plateau” below means equal values at adjacent L. A return to r*=1 after a dip is listed separately. Orbits are only under multiplication by units modulo N, not a claim about all geometric isometries.','',
        'For odd N the full family is a simplex, with gap 2N/(N−1). For even N its gap is 2 at even station steps and 2+4/N at odd steps, so r*=1. The requested simplex bound sqrt(N/(N−1)) remains a valid upper bound but is not attained by the full even family. Giving the Nyquist component half the squared radius would change this model.','',
        'In the tables, an orbit entry size×count records the number of orbits of that size. A mix d:c lists c multipliers of gcd class d; the final ×count counts tied sets with that mix. Every individual set, its mix, and its orbit membership are saved in curves.json.','']
    for c in data['curves']:
        N, rows = c['N'], c['rows']
        lines += [f'## N={N}', '', f"Exhaustively checked {c['subsets_searched']:,} subsets in {c['wall_seconds']:.3f} seconds. Phi_N(z) = {c['cyclotomic_polynomial']}. Simplex ceiling: {c['simplex_ceiling_exact']} = {c['simplex_ceiling']:.12f}.", '',
                  '| L | Dimension | Best gap | r* | Ties | Orbit size×count | Gcd class mixes × set count |','|---:|---:|---:|---:|---:|---|---|']
        for r in rows:
            gap = r['exact_gap']['formula'] if r['gap_is_rational'] else r['exact_gap']['short_closed_form'] or f"{r['gap']:.10f}"
            orbs = ', '.join(f'{s}×{n}' for s,n in sorted(Counter(o['size'] for o in r['orbits']).items()))
            mixes = '; '.join(','.join(f'{d}:{n}' for d,n in sorted(p['class_mix'].items(),key=lambda x:int(x[0])))+f" ×{p['sets']}" for p in r['class_mix_summary'])
            lines += [f"| {r['L']} | {r['dimension']} | {gap} | {r['r_star']:.10f} | {r['ties']} | {orbs} | {mixes} |"]
        classes = sorted({math.gcd(m,N) for m in range(1,c['L_max']+1)})
        dropwords = ', '.join(f'{a} to {b}' for a,b in c['decreases']) or 'none'
        platwords = ', '.join(f'{a} to {b}' for a,b in c['adjacent_plateaus']) or 'none'
        multi = [r['L'] for r in rows if len(r['orbits'])>1]
        lines += ['',prose[N], '',f"Decreases: {dropwords}. Adjacent plateaus: {platwords}. Exact r*=1 sizes: {c['exact_r1_rows']}. Multiple unit orbits: {multi}.", '',
                  'Exact gap forms for nonrational rows (z=exp(2*pi*i/N)):', '']
        for r in rows:
            if not r['gap_is_rational']:
                lines += [f"- L={r['L']}: `{r['exact_gap']['formula']}`."]
        lines += ['']
    lines += ['## Frozen prediction assessments','','Predictions were not edited. Each compound prediction holds only if every stated clause holds.','', '| Prediction | Result |','|---|---|']
    lines += [f'| {k} | {v} |' for k,v in data['prediction_assessments'].items()]
    lines += ['', 'Twenty predictions held and four failed. The failures are 29-M (the L=4 to 5 dip), 30-P (unpredicted exact levels at L=10 and 12), 26-M (the L=7 to 8 dip), and 26-T (two unit orbits at L=5 and 9). Successful parts of a failed compound prediction do not rescue it. The separate runtime expectation of under ten minutes and memory expectation below 1 GiB both held.', '',
              'The strongest interpretation supported here is that subgroup structure helps explain exact level returns, but mixing gcd classes is not necessary for a dip. N=29 rules out that stronger explanation. Every one of the six curves has at least one decrease under the equal-radius constraint.']
    lines += ['', '## Execution record','', '```json',json.dumps(data['environment'],indent=2),'```','',
              f"Final execution wall time: {data['wall_seconds']:.3f} seconds, from prediction verification through all searches, the independent exhaustive verification and figure rendering, excluding JSON/report serialization. Peak process RSS: {data['peak_rss_bytes']:,} bytes. The initial search and first figure rendering took 9.450 seconds; subsequent executions added verification and reporting improvements. Predictions remained unchanged throughout.", '',
              'The numerical result tests this finite family. Factorisation supplies the gcd classes and available subgroup structures; this run does not prove that a factorisation label alone determines every optimal set or every dip. No physical hardware or phase prime metric was tested.']
    (HERE/'report.md').write_text('\n'.join(lines)+'\n')


def main():
    start = time.monotonic_ns()
    expected = (HERE/'predictions.sha256').read_text().split()[0]
    assert sha(HERE/'predictions.md') == expected
    script_hash = sha(__file__)
    a,b = atan_inverse(5),atan_inverse(239)
    pi_bounds = (16*a[0]-4*b[1],16*a[1]-4*b[0])
    curves = [geometry(N,pi_bounds) for N in COUNTS]
    assessments = {k:v for c in curves for k,v in assess(c).items()}
    mpl = plot(curves)
    def sysctl(key):
        try:
            return subprocess.check_output(['/usr/sbin/sysctl','-n',key],text=True).strip()
        except (OSError,subprocess.CalledProcessError):
            return 'unavailable'
    environment = {'python':sys.version,'executable':sys.executable,'platform':platform.platform(),
                   'machine':platform.machine(),'processor':sysctl('machdep.cpu.brand_string'),
                   'logical_cpus':os.cpu_count(),'ram_bytes':sysctl('hw.memsize'),'matplotlib':mpl,
                   'arithmetic':'stdlib arbitrary-precision integers and Decimal; no NumPy computation'}
    rss = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
    data = {'completed_utc':datetime.now(timezone.utc).isoformat(),'script_sha256':script_hash,
            'parent_script_sha256':PARENT_SHA,'predictions_sha256':expected,'plot_sha256':sha(HERE/'curves.png'),
            'environment':environment,'wall_seconds':(time.monotonic_ns()-start)/1e9,
            'peak_rss_bytes':rss if sys.platform=='darwin' else rss*1024,
            'interval_scale':str(Q),'pi_interval_scaled':list(map(str,pi_bounds)),
            'method':'Gray enumeration of every subset; integer interval ordering and exact cyclotomic equality; no fallback',
            'curves':curves,'prediction_assessments':assessments}
    assert sha(HERE/'predictions.md') == expected
    (HERE/'curves.json').write_text(json.dumps(data,indent=2)+'\n')
    report(data)
    for key,val in assessments.items():
        print(key,val)
    print(f"Wall seconds: {data['wall_seconds']:.3f}; peak RSS bytes: {data['peak_rss_bytes']}")


if __name__ == '__main__':
    main()
