#!/usr/bin/env python3
"""Render measured server output, including a common-scale chart. Usage: render-captures.py BASE_DIR HEAD_DIR OUTPUT_DIR."""
import sys,json,math,html,subprocess
from pathlib import Path
base,head,out=map(Path,sys.argv[1:]);out.mkdir(parents=True,exist_ok=True)
reports=[json.loads((p/'measurement.json').read_text()) for p in [base,head]]
scale=math.ceil(max(b['maxMs'] for r in reports for b in r['batches'])/50)*50
for label,p,r in zip(['before','after'],[base,head],reports):
 v=json.loads((p/'malformed-and-plan.json').read_text()); els=['<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="820"><rect width="1200" height="820" fill="#f8fafc"/>']
 def text(x,y,s,size=20,color='#172033'):
  els.append(f'<text x="{x}" y="{y}" font-family="DejaVu Sans" font-size="{size}" fill="{color}">{html.escape(str(s))}</text>')
 color='#c2410c' if label=='before' else '#047857'
 text(45,48,f'{label.title()}: historical usage-limit recovery lookup',30)
 text(45,80,r['commit'],19)
 env=r['environment'];text(45,114,f"{env['os']} {env['architecture']} | Node {env['node']} | SQLite {env.get('nodeSqlite','unknown')}",18)
 text(45,145,'4,000 threads | 60,000 runs | 120,000 items | 40,000 failed errors | 400 usage-limit errors',19)
 text(45,177,'5 warmups, then 3 batches of 25 settings-triggered real-server sweeps',19)
 text(45,210,'Candidate lookup duration (ms); common scale; line = min to max, dot = median',18)
 x0=170;width=940
 for tick in range(0,scale+1,50):
  x=x0+width*tick/scale
  els.append(f'<path d="M{x} 235 V465" stroke="#cbd5e1"/>');text(x-12,492,tick,16)
 for i,b in enumerate(r['batches']):
  y=270+i*80;lo=x0+width*b['minMs']/scale;hi=x0+width*b['maxMs']/scale;mid=x0+width*b['medianMs']/scale
  text(45,y+5,f"Batch {i+1}",20)
  els.append(f'<path d="M{lo} {y} H{hi}" stroke="{color}" stroke-width="8"/><circle cx="{mid}" cy="{y}" r="9" fill="{color}"/>')
  text(170,y+30,f"median {b['medianMs']:.3f} ms | min {b['minMs']:.3f} | max {b['maxMs']:.3f}",17)
 text(45,540,'Recovery eligibility: '+('preserved' if r['eligibilityPreserved'] else 'FAILED'),22)
 text(45,573,'Armed exactly fixture-thread-0000, 0001 and 0002; five ineligible controls stayed unarmed.',18)
 text(45,608,"Malformed payload writable; "+('excluded safely; server recovery sweep succeeds.' if v['realServerRecoverySweepSucceeded'] else 'prefilter and real server sweep fail: malformed JSON.'),18)
 idx='usage_limit_idx' if any('usage_limit_idx' in x for x in v['plan']) else 'failed_error_idx'
 due=json.loads((p/'due-selection.json').read_text())
 text(45,643,'Due selection: same three continuation requests; synthetic provider prevents model execution.',18)
 text(45,677,f'Query plan uses orchestration_v2_projection_turn_items_{idx}',17)
 text(45,735,'Span timings measure candidate selection, not total recovery or UI latency.',18)
 text(45,775,'Synthetic data only. Raw samples and reproducible drivers accompany this capture.',17)
 els.append('</svg>');svg=out/f'{label}.svg';svg.write_text(''.join(els));subprocess.run(['convert',str(svg),str(out/f'{label}.png')],check=True)
# A compact text capture is useful without an image viewer.
lines=['REAL SERVER USAGE-LIMIT RECOVERY COMPARISON','', 'Same Linux machine; separate clean databases migrated by each commit.','Settings snooze toggles invalidate the real UsageLimitRecoveryWorker.','5 warmups + 3 batches of 25 measured ProjectionStore.getLimitRecoveryCandidates spans.','']
for label,p,r in zip(['BEFORE','AFTER'],[base,head],reports):
 lines += [label+' '+r['commit'],json.dumps(r['environment'])]
 for b in r['batches']:lines.append(f"Batch {b['batch']}: median {b['medianMs']:.6f} ms, min {b['minMs']:.6f}, max {b['maxMs']:.6f}")
 lines += ['Armed IDs: '+', '.join(r['armedThreadIds']),'Eligibility preserved: '+str(r['eligibilityPreserved']), (p/'malformed-and-plan.json').read_text(),(p/'due-selection.json').read_text(),'']
med=[[b['medianMs'] for b in r['batches']] for r in reports]
gap=min(med[0])-max(med[1]);spread=max(max(x)-min(x) for x in med)
lines += [f'Smallest base median minus largest head median: {gap:.6f} ms',f'Largest within-side spread between batch medians: {spread:.6f} ms',f'Improvement exceeds spread: {gap>spread}', f'Largest range across individual samples: {max(max(b["maxMs"] for b in r["batches"])-min(b["minMs"] for b in r["batches"]) for r in reports):.6f} ms','Scope: lookup latency, automatic arming and due selection. Does not execute a real provider continuation.']
(out/'comparison.txt').write_text('\n'.join(lines))
