import pathlib,json,subprocess,textwrap,sys
out=pathlib.Path(sys.argv[1])
for side in ['before','after']:
 events=[json.loads(s) for s in (out/(side+'.cast')).read_text().splitlines()[1:]]
 text=''; frames=[]
 for i,(at,kind,chunk) in enumerate(events):
  text+=chunk
  wrapped='\n'.join('\n'.join(textwrap.wrap(l,width=108,replace_whitespace=False,drop_whitespace=False)) if l else '' for l in text.splitlines())
  txt=out/f'{side}-frame-{i}.txt';txt.write_text(wrapped)
  frame=out/f'{side}-frame-{i}.png'
  subprocess.run(['convert','-size','1280x900','xc:#10151d','-fill','#e1e8f0','-font','DejaVu-Sans-Mono','-pointsize','18','-interline-spacing','4','-annotate','+30+40',wrapped,str(frame)],check=True)
  duration=events[i+1][0]-at if i+1<len(events) else 4
  frames.append((frame,max(duration,.1)))
 (out/(side+'-frames.txt')).write_text(''.join(f"file '{p}'\nduration {d}\n" for p,d in frames)+f"file '{frames[-1][0]}'\n")
 subprocess.run(['ffmpeg','-y','-loglevel','error','-f','concat','-safe','0','-i',str(out/(side+'-frames.txt')),'-vf','fps=15','-c:v','libx264','-pix_fmt','yuv420p',str(out/(side+'.mp4'))],check=True)
 subprocess.run(['cp',str(frames[-1][0]),str(out/(side+'.png'))],check=True)
