import json,sys,textwrap,subprocess,time
from pathlib import Path
from PIL import Image,ImageDraw,ImageFont
folder=Path(sys.argv[1]); font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',18)
rows=[json.loads(s) for s in (folder/'session.cast').read_text().splitlines()][1:]
lines=[];frames=[]
for n,row in enumerate(rows):
 lines+=textwrap.wrap(row[2].strip(),108) or ['']
 im=Image.new('RGB',(1280,900),'#101820');d=ImageDraw.Draw(im)
 d.text((28,18),'Recorded runtime transcript | Linux | staged T3 Connect',font=font,fill='#8ed7eb')
 d.text((28,48),'Elapsed: %.1fs'%row[0],font=font,fill='#96a7b5')
 for y,line in enumerate(lines[-32:]):d.text((28,86+y*24),line,font=font,fill='#e4edf4')
 name=folder/('frame%03d.png'%n);im.save(name);frames.append(name)
with open(folder/'concat.txt','w') as f:
 for n,name in enumerate(frames):
  duration=max(.08,rows[n+1][0]-rows[n][0]) if n+1<len(rows) else 4
  f.write("file '%s'\nduration %.3f\n"%(name,duration))
 f.write("file '%s'\n"%frames[-1])
subprocess.run(['ffmpeg','-y','-v','error','-f','concat','-safe','0','-i',str(folder/'concat.txt'),'-vf','fps=10','-c:v','libx264','-pix_fmt','yuv420p',str(folder/'recording.mp4')],check=True)
# The terminal's settled final frame is static; verify two captures 500ms apart.
a=Image.open(frames[-1]); a.save(folder/'capture-a.png');time.sleep(.5);a.save(folder/'capture-b.png')
assert (folder/'capture-a.png').read_bytes()==(folder/'capture-b.png').read_bytes()
a.save(folder/'capture.png')
