import pathlib,json,subprocess,sys,textwrap
run=pathlib.Path(sys.argv[1])
for side in ['before','after']:
    d=run/side
    events=[json.loads(l) for l in (d/'terminal.cast').read_text().splitlines()[1:]]
    accumulated='';frames=[]
    for i,event in enumerate(events):
        accumulated+=event[2].replace('\r','')
        text='\n'.join(textwrap.fill(line,105,replace_whitespace=False) if len(line)>105 else line for line in accumulated.splitlines())
        txt=d/f'frame-{i:02}.txt';txt.write_text(text)
        frame=d/f'frame-{i:02}.png'
        subprocess.run(['convert','-size','1280x900','xc:#111827','-font','DejaVu-Sans-Mono','-pointsize','18','-fill','#e5e7eb','-gravity','NorthWest','-annotate','+30+30',text,str(frame)],check=True)
        duration=(events[i+1][0]-event[0]) if i+1<len(events) else 3
        frames.append(f"file '{frame}'\nduration {max(.1,duration):.3f}\n")
    concat=d/'frames.txt';concat.write_text(''.join(frames)+f"file '{frame}'\n")
    subprocess.run(['ffmpeg','-hide_banner','-loglevel','error','-f','concat','-safe','0','-i',str(concat),'-vf','fps=10,format=yuv420p','-c:v','libx264','-movflags','+faststart',str(d/'terminal-recording.mp4')],check=True)
    subprocess.run(['cp',str(frame),str(d/'terminal-final.png')],check=True)
