from PIL import Image,ImageDraw,ImageFont
import json,pathlib,subprocess,textwrap,sys
root=pathlib.Path(sys.argv[1]);font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',18);title=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',24)
for side in ['before','after']:
 d=root/side;record=json.loads((d/'recording.json').read_text())
 def frame(t):
  im=Image.new('RGB',(1600,1080),'#111827');draw=ImageDraw.Draw(im)
  draw.text((30,24),f'{side.upper()} | ACP replay command output recording',font=title,fill='white')
  draw.text((30,65),f"Commit {record['sha']} | Linux | Node {record['node']}",font=font,fill='#9ca3af')
  draw.text((30,100),'Same 5-entry transcript; prompt id 3, then steer id 4 after 500 ms.',font=font,fill='#9ca3af')
  y=155
  for e in record['events']:
   if e['time']>t:continue
   color={'stdin':'#93c5fd','stdout':'#d1fae5','stderr':'#fca5a5','status':'#fde68a','exit':'#fde68a'}[e['channel']]
   txt=f"{e['time']:.3f}s {e['channel']}: {e['text']}"
   for line in textwrap.wrap(txt,136,subsequent_indent='    ',break_long_words=True,break_on_hyphens=False):
    draw.text((30,y),line,font=font,fill=color);y+=26
   y+=10
  draw.text((30,1035),'Captured subprocess stdin/stdout/stderr and status; no adapter or web UI run.',font=font,fill='#9ca3af')
  return im
 proc=subprocess.Popen(['ffmpeg','-loglevel','error','-y','-f','rawvideo','-vcodec','rawvideo','-pix_fmt','rgb24','-s','1600x1080','-r','10','-i','-','-an','-c:v','libx264','-pix_fmt','yuv420p',str(d/'recording.mp4')],stdin=subprocess.PIPE)
 for n in range(60):proc.stdin.write(frame(n/10).tobytes())
 proc.stdin.close();assert proc.wait()==0
 frame(6).save(d/'capture.png');frame(6.5).save(d/'stable.png')
 assert (d/'capture.png').read_bytes()==(d/'stable.png').read_bytes()
