"""
Process a chunk of source indices at n=11. Save accumulating results to JSON.
Usage: python3 n11_chunk.py <start> <end>
"""
import sys, os, json, time
sys.path.insert(0, '/home/claude/build')
from coverage_fast import (
    enumerate_all_triangulations_fast, build_iso_index,
    resolution_classes_fast, min_degree,
)
import pickle

STATE_PKL = '/tmp/n11_state.pkl'
RESULTS_JSON = '/tmp/n11_results.json'

# Load or build state
if os.path.exists(STATE_PKL):
    with open(STATE_PKL, 'rb') as f:
        state = pickle.load(f)
    reps = state['reps']; iso_index = state['iso_index']
    print(f"Loaded {len(reps)} reps from cache")
else:
    t0 = time.time()
    reps = enumerate_all_triangulations_fast(11)
    iso_index = build_iso_index(reps)
    print(f"Built {len(reps)} reps in {time.time()-t0:.1f}s")
    with open(STATE_PKL, 'wb') as f:
        pickle.dump({'reps': reps, 'iso_index': iso_index}, f)

# Load partial results
if os.path.exists(RESULTS_JSON):
    with open(RESULTS_JSON) as f:
        results = {int(k): v for k, v in json.load(f).items()}
else:
    results = {}

start = int(sys.argv[1]); end = int(sys.argv[2])
end = min(end, len(reps))
t1 = time.time()
for i in range(start, end):
    if i in results:
        continue
    res = resolution_classes_fast(reps[i], iso_index)
    results[i] = sorted(res)
    if (i + 1) % 25 == 0:
        elapsed = time.time() - t1
        done = i + 1 - start
        eta = elapsed * (end - start - done) / max(done, 1)
        print(f"  {i+1}/{end} ({elapsed:.0f}s, ETA {eta:.0f}s)", flush=True)
    if (i + 1) % 50 == 0:
        with open(RESULTS_JSON, 'w') as f:
            json.dump({str(k): v for k, v in results.items()}, f)

with open(RESULTS_JSON, 'w') as f:
    json.dump({str(k): v for k, v in results.items()}, f)
print(f"Saved {len(results)} source results. Range [{start},{end}). "
      f"Chunk time: {time.time()-t1:.1f}s")
