import pathlib,json,textwrap,subprocess,sys
from PIL import Image,ImageDraw,ImageFont
root=pathlib.Path(sys.argv[1]);font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',19);small=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',16)
for side in ['before','after']:
 out=root/side;all_events=json.loads((out/'recording.json').read_text());events=[];success_seen=False
 for e in all_events:
  if e['text'].startswith('Legacy MCP trace ') and json.loads(e['text'][len('Legacy MCP trace '):])['exit']['_tag']=='Success':
   if success_seen:continue
   success_seen=True
  events.append(e)
 lines=[];concat=[]
 for i,e in enumerate(events):
  lines.append('['+e['utc'][11:19]+' UTC | +'+str(e['elapsed'])+'s]')
  text=e['text']
  if text.startswith('Legacy MCP trace '):
   z=json.loads(text[len('Legacy MCP trace '):]);text=z['name']+' -> '+z['exit']['_tag']
   if z['exit'].get('cause'):text+='\n'+'\n'.join(z['exit']['cause'].splitlines()[:2])
  if text.startswith('CLI runtime recording'):text+='\nParent model: opencode/big-pickle; delegated child: DeepSeek (low).'
  for l in text.splitlines():lines.extend(textwrap.wrap(l,128,replace_whitespace=False) or [''])
  lines.append('')
  im=Image.new('RGB',(1600,1000),'#101418');d=ImageDraw.Draw(im)
  d.text((30,22),side.upper()+' | Real server / CLI runtime capture',font=font,fill='#87d7ff')
  d.text((30,58),'Selected CLI JSON fields and legacy MCP spans. Idle intervals compressed; timestamps preserved.',font=small,fill='#bac2cb')
  d.line((30,90,1570,90),fill='#39444d')
  for n,line in enumerate(lines[-34:]):d.text((30,110+n*25),line,font=font,fill='#e5e8eb')
  d.text((30,970),'Linux x64 | Parent: Big Pickle | Child: DeepSeek (low) | Legacy: 20261110.4449',font=small,fill='#bac2cb')
  f=out/f'frame-{i:04d}.png';im.save(f)
  duration=3 if i==len(events)-1 else min(3,max(.8,events[i+1]['elapsed']-e['elapsed']))
  concat.extend(["file '"+str(f)+"'",'duration '+str(duration)])
 summary=[all_events[0]]
 child=next((e for e in reversed(all_events) if e['text'].startswith('$ legacy-t3 thread show') and '"completed"' in e['text']),None)
 failure=next((e for e in reversed(all_events) if e['text'].startswith('Legacy MCP trace ') and '"Failure"' in e['text']),None)
 parent=next((e for e in reversed(all_events) if e['text'].startswith('$ t3 thread show')),None)
 summary.extend(e for e in [child,failure,parent,all_events[-1]] if e)
 im=Image.new('RGB',(1600,1000),'#101418');d=ImageDraw.Draw(im)
 d.text((30,22),side.upper()+' | CLI transcript excerpt',font=font,fill='#87d7ff')
 d.text((30,58),'Real server outputs | Parent: OpenCode Big Pickle | Child: OpenCode DeepSeek (low)',font=small,fill='#bac2cb')
 d.line((30,90,1570,90),fill='#39444d');rows=[]
 for e in summary:
  rows.append('['+e['utc'][11:19]+' UTC | +'+str(e['elapsed'])+'s]')
  t=e['text']
  if t.startswith('Legacy MCP trace '):
   z=json.loads(t[len('Legacy MCP trace '):]);t=z['name']+' -> '+z['exit']['_tag']+'\n'+'\n'.join(z['exit']['cause'].splitlines()[:2])
  for l in t.splitlines():rows.extend(textwrap.wrap(l,128,replace_whitespace=False) or [''])
  rows.append('')
 for n,line in enumerate(rows):d.text((30,110+n*25),line,font=font,fill='#e5e8eb')
 assert len(rows)<=34, len(rows)
 f=out/(side+'.png');im.save(f);concat.extend(["file '"+str(f)+"'",'duration 5'])
 (out/'video.txt').write_text('\n'.join(concat)+"\nfile '"+str(f)+"'\n")
 subprocess.run(['ffmpeg','-y','-v','error','-f','concat','-safe','0','-i',str(out/'video.txt'),'-vf','fps=10','-c:v','libx264','-crf','22','-pix_fmt','yuv420p',str(out/(side+'.mp4'))],check=True)
 transcript='\n\n'.join('['+e['utc']+' | +'+str(e['elapsed'])+'s]\n'+e['text'] for e in all_events)
 (out/(side+'.txt')).write_text(transcript+'\n')
