import json,pathlib,sys,re,textwrap,subprocess
from PIL import Image, ImageDraw, ImageFont
root=pathlib.Path(sys.argv[1]); events=json.loads((root/'terminal-recording.json').read_text())
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',20)
small=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',17)
def clean(s): return re.sub(r'/tmp/claude-[^\s`]+','[task output path redacted]',s)
# Record the actual driver output with its original timestamps, redacting paths only.
cast=[json.dumps({'version':2,'width':118,'height':40,'timestamp':0,'env':{'TERM':'xterm-256color'}})]
for t,s in events: cast.append(json.dumps([t,'o',clean(s)+'\r\n']))
(root/'session.cast').write_text('\n'.join(cast)+'\n')
(root/'transcript.txt').write_text('\n'.join(f'[{t:6.1f}s] '+clean(s) for t,s in events)+'\n')
# Compact repeated task metadata for readable video; raw transcript is also supplied.
lines=[]; pages=[]; phase=''
for t,s in events:
 s=clean(s)
 if s.startswith('  persisted pendingBackgroundTasks: '):
  tasks=json.loads(s.split(': ',1)[1]); flat=[a for group in tasks for a in group]
  s='  persisted tasks: '+json.dumps([{k:a[k] for k in ('command','taskId','awaited') if k in a} for a in flat])
 if s in ('BEFORE RESTART','AFTER RESTART') or s.startswith('Observed for another'):
  lines=[]; phase=s
 if s.startswith('BASE ') or s.startswith('HEAD '): title=s
 lines += textwrap.wrap(f'[{t:.1f}s] '+s,width=108,replace_whitespace=False,drop_whitespace=False) or ['']
 lines=lines[-29:]
 im=Image.new('RGB',(1440,900),'#10141c'); d=ImageDraw.Draw(im)
 d.text((30,20),'Real T3 server / Claude CLI output — '+root.name.split('-')[0],font=font,fill='#edf3fa')
 d.text((30,55),title[:110],font=small,fill='#9fb6d2')
 d.text((30,85),'Linux • Claude haiku • fresh isolated data • '+phase,font=small,fill='#91cbb7')
 y=130
 for line in lines: d.text((30,y),line,font=font,fill='#edf3fa'); y+=25
 file=root/f'frame-{len(pages):03}.png'; im.save(file); pages.append((t,file))
# Preserve elapsed time between output events. Last view held for 5 seconds.
concat=[]
for i,(t,p) in enumerate(pages):
 dur=(pages[i+1][0]-t) if i+1<len(pages) else 5
 concat.extend(["file '"+str(p)+"'",'duration '+str(max(.1,dur))])
concat.append("file '"+str(pages[-1][1])+"'")
(root/'frames.txt').write_text('\n'.join(concat))
subprocess.run(['ffmpeg','-v','error','-y','-f','concat','-safe','0','-i',str(root/'frames.txt'),'-vf','fps=5','-c:v','libx264','-pix_fmt','yuv420p',str(root/'recording.mp4')],check=True)
pages[-1][1].replace(root/'final.png')
for name in ('before-restart','after-restart','final'):
 data=json.loads((root/(name+'.json')).read_text())
 for a in data.values():
  a['commandItems']=[{k:clean(str(v)) for k,v in p.items() if k in ('input','output','status','startedAt','completedAt')} for p in a['commandItems']]
  for m in a['messages']: m['text']=clean(m['text'])
 (root/(name+'-public.json')).write_text(json.dumps(data,indent=2))
