from PIL import Image, ImageDraw, ImageFont
import json,pathlib,sys,textwrap,subprocess
root=pathlib.Path(sys.argv[1]); font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',20); title=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',26)
for side,sha in [('before','49d434a36e'),('after','8a93d38fbf')]:
 p=root/side; frames=json.loads((p/'frames.json').read_text()); imgs=p/'slides'; imgs.mkdir()
 def draw(body,dest):
  im=Image.new('RGB',(1600,1080),'#10151d'); d=ImageDraw.Draw(im)
  d.text((35,25),f'{side.upper()} | {sha} | Real server + CLI | Linux | fresh database',font=title,fill='#ecf2ff')
  d.text((35,70),'Captured CLI output (JSON pretty-printed for readability)',font=font,fill='#9aa9bf')
  y=115
  for line in body.splitlines():
   for row in textwrap.wrap(line,124,replace_whitespace=False,drop_whitespace=False) or ['']:
    d.text((35,y),row,font=font,fill='#7ee2ba' if row.startswith('$') else '#e1e7f0'); y+=24
  if y>1070: raise RuntimeError('clipped frame')
  im.save(dest)
 for i,f in enumerate(frames):
  command,output=f.split('\n',1)
  try: output=json.dumps(json.loads(output),indent=2)
  except: pass
  draw(command+'\n'+output,imgs/f'{i:03}.png')
 summary='\n\n'.join([frames[2],frames[8],frames[12],frames[-1]])
 draw(summary,p/f'{side}.png')
 subprocess.run(['ffmpeg','-y','-loglevel','error','-framerate','1/3','-i',str(imgs/'%03d.png'),'-c:v','libx264','-r','30','-pix_fmt','yuv420p',str(p/f'{side}.mp4')],check=True)
