import json
from PIL import Image, ImageDraw, ImageFont
from pathlib import Path
root=Path(__file__).parent
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',18)
bold=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono-Bold.ttf',22)
for side in ['base','head']:
 d=json.loads((root/(side+'-final.json')).read_text())
 im=Image.new('RGB',(960,940),'#111827'); draw=ImageDraw.Draw(im)
 draw.text((28,24),('BEFORE' if side=='base' else 'AFTER')+' | Pi connection teardown',font=bold,fill='white')
 lines=[d['commit'],'Linux x64 | Node '+d['node']+' | kernel '+d['kernel'],'Production RPC + live clock + real Node child','Ready -> close connection scope -> process group absent','','iteration   close (ms)   SIGTERM   exit code   group gone']
 lines += [f"{r['iteration']:>5}       {r['elapsedMs']:>9.3f}     yes          0          yes" for r in d['rows']]
 lines += ['',f"Median {d['medianMs']:.3f} ms | range {d['minMs']:.3f}-{d['maxMs']:.3f} ms",f"Spread {d['spreadMs']:.3f} ms | 20/20 identical shutdown outcomes"]
 for i,line in enumerate(lines): draw.text((28,72+i*25),line,font=font,fill='#d1fae5' if i>25 else '#e5e7eb')
 draw.rectangle((28,855,28+int(d['medianMs']/1100*850),880),fill='#fb923c' if side=='base' else '#34d399')
 draw.text((28,895),'Median on shared 0-1100 ms scale',font=font,fill='#9ca3af')
 im.save(root/(side+'.png'))
