from pathlib import Path
import json,subprocess
from PIL import Image,ImageDraw,ImageFont
ROOT=Path(__file__).resolve().parent
runs=sorted(ROOT.glob('run-*/evidence.json'))
complete=json.loads(runs[-2].read_text()); interrupted=json.loads(runs[-1].read_text())
OUT=ROOT/'public';OUT.mkdir(exist_ok=True)
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',21)
big=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',29)
small=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',17)
for side in ['before','after']:
 frames=OUT/(side+'-frames');frames.mkdir(exist_ok=True)
 index=0
 for phase,data in [('Slow lookup: allowed to complete',complete),('Interrupt: SIGTERM to the real server',interrupted)]:
  d=data['sides'][side]
  for n,s in enumerate(d['samples']):
   im=Image.new('RGB',(1280,720),'#10151d');draw=ImageDraw.Draw(im)
   draw.text((40,28),side.upper()+' | Real T3 server / npm cache monitor',font=big,fill='#f4f7fb')
   draw.text((40,79),'Commit '+d['sha'],font=small,fill='#a9b8cb')
   draw.text((40,125),phase,font=font,fill='#8ecbff')
   draw.text((40,164),'Elapsed since server spawn: '+str(s['elapsed'])+' s',font=font,fill='white')
   draw.text((40,209),'Synthetic Codex 0.172.0, manual binary path',font=font,fill='#a9b8cb')
   draw.text((40,241),'Local registry: 19.6 MB packument, 64 KiB / 100 ms',font=font,fill='#a9b8cb')
   y=300
   for title,key in [('Shared npm cache','shared'),('T3-owned npm cache','t3')]:
    files=s[key];total=sum(x['bytes'] for x in files)
    draw.text((40,y),title,font=font,fill='white')
    draw.text((540,y),f'{len(files)} partial files | {total:,} bytes',font=font,fill='#ffcd85' if total else '#a8e5bd');y+=48
   cmds=s.get('processes',[])
   if cmds:
    draw.text((40,418),cmds[0]['command'][:95],font=small,fill='#a9b8cb')
    cache=cmds[0]['cache'];draw.text((40,448),'npm cache: '+cache[:106],font=small,fill='#a9b8cb')
   final=n==len(d['samples'])-1
   if final:
    draw.text((40,505),'Server stopped; final cache inventory above.',font=font,fill='#a8e5bd')
   else:draw.text((40,505),'Monitoring actual files under _cacache/tmp',font=font,fill='#a9b8cb')
   draw.text((40,590),'Recorded filesystem samples, rendered as a terminal monitor.',font=small,fill='#8799b0')
   draw.text((40,620),'Both commits already lack the reported 10-second npm timeout.',font=small,fill='#ffcd85')
   repeats=6 if final else 1
   for _ in range(repeats):
    im.save(frames/f'{index:05}.png');index+=1
   if final:im.save(OUT/(side+('-complete.png' if data is complete else '-interrupted.png')))
  if phase.startswith('Interrupt'):
   peak=max(d['samples'],key=lambda x:sum(f['bytes'] for f in x['shared']+x['t3']))
   print(side,'peak bytes',sum(f['bytes'] for f in peak['shared']+peak['t3']),'final',d['samples'][-1])
 subprocess.run(['ffmpeg','-hide_banner','-loglevel','error','-framerate','2','-i',str(frames/'%05d.png'),'-c:v','libx264','-pix_fmt','yuv420p','-crf','22','-movflags','+faststart','-y',str(OUT/(side+'.mp4'))],check=True)
(OUT/'completion-evidence.json').write_text(json.dumps(complete,indent=2))
(OUT/'interruption-evidence.json').write_text(json.dumps(interrupted,indent=2))
print('Artifacts rendered')
