"""Render recorded terminal events to video; no output is synthesized or rewritten."""
import json,sys,pathlib,subprocess
cast=pathlib.Path(sys.argv[1]); events=[json.loads(l) for l in cast.read_text().splitlines()[1:]]
concat=[];images=[]
for i,e in enumerate(events):
 text=e[2].replace('\x1b[2J\x1b[H','').replace('\r','')
 if len(text.splitlines())>40:raise Exception('Clipped terminal frame')
 image=cast.parent/f'frame-{i:02}.png';images.append(str(image))
 subprocess.run(['convert','-size','1320x900','xc:#10151d','-font','DejaVu-Sans-Mono','-pointsize','18','-fill','#e6edf3','-annotate','+24+30',text,str(image)],check=True)
 concat.extend([f"file '{image}'",f'duration {max(3,events[i+1][0]-e[0]) if i+1<len(events) else 5:.3f}'])
concat.append(f"file '{images[-1]}'"); listing=cast.parent/'frames.txt';listing.write_text('\n'.join(concat))
subprocess.run(['ffmpeg','-hide_banner','-loglevel','error','-y','-f','concat','-safe','0','-i',str(listing),'-vf','fps=10','-c:v','libx264','-preset','fast','-crf','20','-pix_fmt','yuv420p','-movflags','+faststart',str(cast.with_suffix('.mp4'))],check=True)
subprocess.run(['montage',*images,'-thumbnail','660x450','-tile','2x','-geometry','+4+4',str(cast.parent/'review.png')],check=True)
