import pathlib,json,textwrap,subprocess,sys
from PIL import Image,ImageDraw,ImageFont
root=pathlib.Path(__file__).parent
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',22)
small=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',19)
for name in sys.argv[1:]:
 run=root/name; events=json.loads((run/'events.json').read_text()); end=events[-1]['time']+4
 def frame(t):
  im=Image.new('RGB',(1920,1200),'#10151d'); d=ImageDraw.Draw(im)
  d.text((35,22),'T3 Code | real server / CLI capture | Linux',font=font,fill='#99c8ff')
  d.text((35,58),'Timestamped transcript playback; scratch and home paths redacted. No server restart.',font=small,fill='#aab8c8')
  lines=[]
  for e in events:
   if e['time']<=t:
    for line in e['text'].splitlines():
     lines.extend(textwrap.wrap(line, width=137,replace_whitespace=False,drop_whitespace=False) or [''])
  for i,l in enumerate(lines[-36:]):
   color='#f1f5fa'
   if 'ENOENT' in l or 'PlatformError' in l: color='#ff9d9d'
   elif 'ACTION:' in l: color='#ffd381'
   elif 'Server trace, cumulative' in l: color='#8ee0bb'
   d.text((35,110+i*28),l,font=font,fill=color)
  d.text((35,1155),f'Elapsed {min(t,events[-1]["time"]):.1f}s  |  Captured subprocess output + server trace; no test assertions',font=small,fill='#aab8c8')
  return im
 frame(end).save(run/'capture.png')
 proc=subprocess.Popen(['ffmpeg','-y','-loglevel','error','-f','rawvideo','-pix_fmt','rgb24','-s','1920x1200','-r','5','-i','-','-an','-c:v','libx264','-preset','fast','-crf','22','-pix_fmt','yuv420p',str(run/'capture.mp4')],stdin=subprocess.PIPE)
 for i in range(int(end*5)+1):proc.stdin.write(frame(i/5).tobytes())
 proc.stdin.close(); assert proc.wait()==0
 print(run/'capture.mp4')
