from PIL import Image, ImageDraw, ImageFont
import pathlib,json,subprocess,textwrap,sys
root=pathlib.Path(sys.argv[1])
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',23)
small=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',19)
for side,folder in [('before','before-final'),('after','after-final')]:
 events=json.loads((root/'proof-user'/folder/'events.json').read_text())
 def frame(selected):
  im=Image.new('RGB',(1920,1080),'#10151e'); d=ImageDraw.Draw(im)
  d.text((40,24),f'{side.upper()} | Linux | real systemd user service | CLI output recording',font=font,fill='#ffffff')
  d.text((40,62),'Isolated user; fresh unit per run; paths anonymized as $HOME and $PROOF_HOME',font=small,fill='#b4bdcb')
  lines=[]
  for e in selected:
   for line in e['text'].splitlines():
    lines.extend(textwrap.wrap(line,128,replace_whitespace=False,drop_whitespace=False) or [''])
  for i,line in enumerate(lines[-34:]):
   col='#91bfff' if line.startswith('$ ') else '#e0e5ec'
   if 'not installed.' in line: col='#ff9696'
   if 'definition was found' in line or 'could not be determined' in line: col='#9be4b2'
   d.text((40,115+i*27),line,font=font,fill=col)
  d.text((40,1048),'Actual subprocess output, rendered from timestamped capture; no simulated service responses.',font=small,fill='#b4bdcb')
  return im
 frame(events).save(root/(side+'.png'))
 duration=events[-1]['seconds']+5
 proc=subprocess.Popen(['ffmpeg','-y','-loglevel','error','-f','rawvideo','-pix_fmt','rgb24','-s','1920x1080','-r','4','-i','-','-an','-c:v','libx264','-preset','fast','-crf','22','-pix_fmt','yuv420p',str(root/(side+'.mp4'))],stdin=subprocess.PIPE)
 for i in range(int(duration*4)+1):
  proc.stdin.write(frame([e for e in events if e['seconds']<=i/4]).tobytes())
 proc.stdin.close(); assert proc.wait()==0
