from PIL import Image,ImageDraw,ImageFont
import pathlib,json,subprocess,sys,textwrap
root=pathlib.Path(sys.argv[1]); events=json.loads((root/'events.json').read_text()); font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',18)
lines=[]; frames=[]
for i,e in enumerate(events):
 lines+=['']+e['text'].splitlines()
 im=Image.new('RGB',(1440,1080),'#101820'); draw=ImageDraw.Draw(im)
 draw.text((30,18),'REAL CLI OUTPUT • recorded command sequence',font=font,fill='#8cc8ff')
 y=60
 for line in lines:
  for part in textwrap.wrap(line,125) or ['']:
   draw.text((30,y),part,font=font,fill='#e7eef7' if not line.startswith('$') else '#8fe0b0'); y+=23
 p=root/f'frame-{i:02d}.png'; im.save(p); frames.append(p)
(root/'capture.png').write_bytes(frames[-1].read_bytes())
concat=''
for i,p in enumerate(frames):
 duration=(events[i+1]['time']-events[i]['time']) if i+1<len(events) else 5
 concat+=f"file '{p}'\nduration {max(.5,duration)}\n"
concat+=f"file '{frames[-1]}'\n"; (root/'frames.txt').write_text(concat)
subprocess.run(['ffmpeg','-v','error','-f','concat','-safe','0','-i',str(root/'frames.txt'),'-vf','fps=10','-c:v','libx264','-pix_fmt','yuv420p',str(root/'recording.mp4')],check=True)
