"""Render captured terminal.cast to MP4. JSON is reflowed; reading pauses are added.
The source cast preserves original stdout and wall-clock timings.
"""
import json,pathlib,sys,textwrap,subprocess
from PIL import Image,ImageDraw,ImageFont
root=pathlib.Path(sys.argv[1]);side=sys.argv[2]
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',17)
small=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',15)
rows=[];frames=[];last=0
for event in [json.loads(l) for l in (root/'terminal.cast').read_text().splitlines()[1:]]:
 at,_,text=event;text=text.replace('\r','').strip()
 try:
  obj=json.loads(text)
  if 'operations' in obj:
   lines=['TRACE cwd='+obj['cwd'],f"  spanId={obj['spanId']} traceId={obj['traceId']}",f"  gitProcesses={obj['gitProcesses']}"]
   for op in obj['operations']:
    lines.append('  '+op['name']+' exit='+op['exit']['_tag'])
    if op['exit'].get('cause'):lines.append('  '+op['exit']['cause'].split('\n')[0])
  else:lines=json.dumps(obj,indent=2,ensure_ascii=False).splitlines()
 except Exception:lines=text.splitlines()
 newrows=[]
 for line in lines:newrows.extend(textwrap.wrap(line,width=116,replace_whitespace=False,drop_whitespace=False) or [''])
 rows.extend(newrows);rows=rows[-34:]
 img=Image.new('RGB',(1280,900),'#10151e');d=ImageDraw.Draw(img)
 d.text((28,18),'T3 CODE • '+side.upper()+' • real server / CLI output',font=font,fill='#d8e5f7')
 d.text((28,46),'Captured stdout replay • JSON reflowed; pauses added for reading • Linux / OpenCode 2.4.3',font=small,fill='#9faec2')
 for i,row in enumerate(rows):d.text((28,85+i*23),row,font=font,fill='#cdd9e9')
 d.text((28,875),f'Original capture time: {at:.1f}s  •  Exact stdout and timing: terminal.cast',font=small,fill='#9faec2')
 if '/worktrees/multi/' in text:img.save(root/'non-git-terminal.png')
 if '/worktrees/demo/' in text and 'operations' in text:img.save(root/'unborn-terminal.png')
 frames.append((img,max(.5,min(4,at-last))));last=at
frames[-1]=(frames[-1][0],6)
p=subprocess.Popen(['ffmpeg','-y','-loglevel','error','-f','rawvideo','-vcodec','rawvideo','-pix_fmt','rgb24','-s','1280x900','-r','2','-i','-','-an','-c:v','libx264','-preset','fast','-crf','23','-pix_fmt','yuv420p',str(root/'terminal.mp4')],stdin=subprocess.PIPE)
for img,duration in frames:
 for _ in range(max(1,round(duration*2))):p.stdin.write(img.tobytes())
p.stdin.close();p.wait();frames[-1][0].save(root/'terminal-final.png')
