"""Record real driver stdout with original line arrival times into an MP4."""
import subprocess,time,pathlib,sys,textwrap,json
from PIL import Image,ImageDraw,ImageFont
side,work,directory,port=sys.argv[1:];root=pathlib.Path(directory);root.mkdir();frames=root/'frames';frames.mkdir()
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',22)
lines=['T3 Code — ACP native-session recovery',('BASE 8b609772ef' if side=='base' else 'HEAD 8f8cfc5763'),'Linux CLI | agy 1.5.20 | Gemini 3.8 Flash | API-key mode','Fresh database | identical driver | real stdout, original timing','']
def shot(n):
 im=Image.new('RGB',(1440,900),'#111827');d=ImageDraw.Draw(im);y=35
 for line in lines:
  for part in textwrap.wrap(line,100) or ['']:
   d.text((35,y),part,font=font,fill='#e5e7eb');y+=30
 im.save(frames/f'{n:04}.png')
p=subprocess.Popen(['python3',str(pathlib.Path(__file__).with_name('driver.py')),work,str(root/'run'),port],stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True)
t0=time.monotonic();events=[];shot(0)
for line in p.stdout:
 line=line.strip();events.append([time.monotonic()-t0,line]);print(line,flush=True)
 if line:lines.append(line)
 shot(len(events))
p.wait();(root/'stdout-events.json').write_text(json.dumps(events,indent=2));shot(9999)
entries=[];last=0
for n in range(len(events)+1):
 t=0 if n==0 else events[n-1][0]
 if entries:entries[-1][1]=max(.1,t-last)
 entries.append([frames/f'{n:04}.png',1]);last=t
entries[-1][1]=5
manifest=root/'frames.txt';manifest.write_text(''.join("file '"+str(f)+"'\nduration "+str(d)+'\n' for f,d in entries)+"file '"+str(entries[-1][0])+"'\n")
subprocess.run(['ffmpeg','-y','-loglevel','error','-f','concat','-safe','0','-i',str(manifest),'-vf','fps=10','-c:v','libx264','-pix_fmt','yuv420p',str(root/'capture.mp4')],check=True)
sys.exit(p.returncode)
