import json,pathlib,subprocess,textwrap
from PIL import Image,ImageDraw,ImageFont
root=pathlib.Path(__file__).parent
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',17)
for name in ['before-20261111T092719Z','after-20261111T092728Z']:
 p=root/name
 records=[json.loads(l) for l in (p/'session.cast').read_text().splitlines()][1:]
 duration=records[-1][0]+3
 proc=subprocess.Popen(['ffmpeg','-y','-v','error','-f','rawvideo','-pix_fmt','rgb24','-s','1440x900','-r','4','-i','-','-c:v','libx264','-pix_fmt','yuv420p',str(p/'session.mp4')],stdin=subprocess.PIPE)
 for frame in range(int(duration*4)+1):
  t=frame/4
  contents=''.join(r[2] for r in records if r[0]<=t)
  im=Image.new('RGB',(1440,900),'#10151c');draw=ImageDraw.Draw(im)
  draw.text((28,20),'LIVE SERVER / CLI RECORDING — '+name.split('-')[0].upper(),font=font,fill='#8ecbff')
  y=62
  for line in contents.splitlines():
   for part in textwrap.wrap(line,132,replace_whitespace=False) or ['']:
    color='#f8a59c' if 'Failure' in part or 'Query closed' in part else '#cde8ce' if 'Success' in part else '#e2e8f0'
    draw.text((28,y),part,font=font,fill=color);y+=24
  proc.stdin.write(im.tobytes())
 im.save(p/'session.png');proc.stdin.close()
 if proc.wait():raise RuntimeError('ffmpeg failed')
 print(p)
