"""Render the actual captured JSON measurements as a readable PNG and text transcript.
Usage: python3 render-evidence.py OUT BASE_ROUND_1 HEAD_ROUND_1 HEAD_ROUND_2 BASE_ROUND_2
Each round argument is a directory containing measurements.jsonl and summary.json.
"""
import sys,json,statistics
from pathlib import Path
from PIL import Image,ImageDraw,ImageFont
out=Path(sys.argv[1]);out.mkdir(exist_ok=True,parents=True)
rounds=[Path(p) for p in sys.argv[2:]]
summaries=[json.loads((p/'summary.json').read_text()) for p in rounds]
base=[summaries[0],summaries[3]];head=[summaries[1],summaries[2]]
font_path='/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf'
mono_path='/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf'
def font(size,mono=False):return ImageFont.truetype(mono_path if mono else font_path,size)
all_rows=[]
for p in rounds:
 rows=[json.loads(s) for s in (p/'measurements.jsonl').read_text().splitlines()]
 all_rows.extend(rows)
assert all(r['interruptRecorded'] and r['terminalStatus']=='interrupted' for r in all_rows if r['kind'] in ('sample','warmup'))
merged={'base':base,'head':head,'order':'base / head / head / base','sampleCount':sum(r['kind']=='sample' for r in all_rows),'warmupCount':sum(r['kind']=='warmup' for r in all_rows),'sameBehavior':True}
(out/'comparison.json').write_text(json.dumps(merged,indent=2)+'\n')
for side,items in [('before',base),('after',head)]:
 lines=['STOP HISTORY PERFORMANCE — '+side.upper(),f'Commit: {items[0]["sha"]}','Linux x64 | Node 26.13.1 | file-backed SQLite | real server', 'Authenticated WebSocket RPC; repository Replay (dev) provider.', '5,000 completed turns seeded via app RPC, no inserted database rows.', 'Each round: 4 warmups + 36 measured samples per action.', 'Timing: dispatch request to RPC acknowledgement, in milliseconds.', 'Provider shutdown awaited after timing.', '']
 for idx,s in enumerate(items,1):
  lines.append(f'Round {idx}')
  for a,v in s['actions'].items():lines.append(f'  {a:14s}: median {v["median"]:.2f} ms; min–max {v["min"]:.2f}–{v["max"]:.2f} ms; n={v["n"]}')
 lines+=['','Every measured sample and warmup recorded run_interrupt_request.', 'Every stopped run reached interrupted status.', 'Raw samples follow.','']
 side_rounds=[rounds[0],rounds[3]] if side=='before' else [rounds[1],rounds[2]]
 for i,p in enumerate(side_rounds,1):
  lines.append(f'=== ROUND {i} ===')
  lines.extend((p/'measurements.jsonl').read_text().splitlines())
 (out/f'{side}.txt').write_text('\n'.join(lines)+'\n')
 im=Image.new('RGB',(1500,650),'#10151e');d=ImageDraw.Draw(im)
 d.text((45,30),'Before' if side=='before' else 'After',font=font(34),fill='#f0f4fa')
 d.text((45,82),items[0]['sha'][:10]+' · 5,000 completed runs',font=font(25),fill='#bac5d6')
 d.text((45,128),'Real Linux server · file-backed SQLite · authenticated WebSocket RPC',font=font(22),fill='#bac5d6')
 y=200
 for idx,s in enumerate(items,1):
  d.text((45,y),f'Round {idx} · median (min–max), milliseconds',font=font(25),fill='#f0f4fa');y+=46
  for a,v in s['actions'].items():
   d.text((65,y),f'{a:14s}  {v["median"]:8.2f}  ({v["min"]:.2f}–{v["max"]:.2f})',font=font(27,True),fill='#7dd3fc' if side=='after' else '#f9b572');y+=48
  y+=25
 d.text((45,530),'36 samples/action/round + 4 warmups; same driver and machine.',font=font(23),fill='#bac5d6')
 d.text((45,574),'All interrupt requests recorded; all stopped runs reached interrupted.',font=font(23),fill='#9ce3ba')
 im.save(out/f'{side}.png')
print(json.dumps(merged,indent=2))
