import json,pathlib,sys,textwrap,subprocess
from PIL import Image,ImageDraw,ImageFont
root=pathlib.Path(sys.argv[1]);side=sys.argv[2];sha=sys.argv[3]
events=json.loads((root/'recording.json').read_text());font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',19);titlefont=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',25)
lines=[];frames=[];action='start'
for i,e in enumerate(events):
 text=e['text']
 if text.startswith('$ t3 thread send'): action='send';text=text.replace(' --provider claudeAgent --model claude-haiku-5-5','')
 # Each event is captured from the live command or read-only run projection.
 if text.startswith(('Stored runs:','Final stored runs:')): 
  rows=json.loads(text.split(': ',1)[1]);text='Stored runs (read-only database):\n'+'\n'.join(json.dumps(r) for r in rows[-(2 if action=='start' else 4):])
 for line in text.splitlines(): lines.extend(textwrap.wrap(line,115,replace_whitespace=False,drop_whitespace=False) or [''])
 im=Image.new('RGB',(1600,1000),'#111820');d=ImageDraw.Draw(im)
 d.text((35,25),side+' | '+sha[:10]+' | Linux CLI + real server',font=titlefont,fill='#ffffff')
 d.text((35,65),'claudeAgent / claude-haiku-5-5 | isolated synthetic state | live transcript',font=font,fill='#9cb0c3')
 d.text((35,105),'Elapsed: %.2fs'%e['seconds'],font=font,fill='#ffcd75')
 for j,line in enumerate(lines[-32:]):d.text((35,150+j*25),line,font=font,fill='#d3e0ec')
 frame=root/('frame-%03d.png'%i);im.save(frame);frames.append(frame)
(root/'final.png').write_bytes(frames[-1].read_bytes())
with (root/'frames.txt').open('w') as f:
 for i,p in enumerate(frames):
  duration=max(.1,(events[i+1]['seconds']-events[i]['seconds']) if i+1<len(events) else 5)
  f.write("file '"+str(p)+"'\nduration "+str(duration)+'\n')
 f.write("file '"+str(frames[-1])+"'\n")
subprocess.run(['ffmpeg','-v','error','-y','-f','concat','-safe','0','-i',str(root/'frames.txt'),'-vf','fps=10','-c:v','libx264','-preset','fast','-crf','23','-pix_fmt','yuv420p',str(root/'recording.mp4')],check=True)
