import sys,json,textwrap,subprocess,math
from pathlib import Path
sys.path.insert(0,str(Path(__file__).parent/'python-libs'))
from PIL import Image,ImageDraw,ImageFont
root=Path(sys.argv[1]); events=json.loads((root/'events.json').read_text());side=root.name.split('-')[0]
sha='c00a373491d20ebcef901b81170abfb9f5f757fe' if side=='before' else 'd164cfac0fad81585c6699988bfc7eaf30e9b4e9'
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',19)
small=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',17)
frames=root/'frames';frames.mkdir()
for second in range(math.ceil(events[-1]['seconds'])+3):
 im=Image.new('RGB',(1440,960),'#10141c'); d=ImageDraw.Draw(im)
 d.text((28,20),side.upper()+' | Service recovery after ownership clears',font=font,fill='#ffffff')
 d.text((28,54),'Commit '+sha,font=small,fill='#9aa9be')
 d.text((28,84),'Linux | real bundled T3 CLI + systemd user service | fresh isolated home',font=small,fill='#9aa9be')
 d.text((28,114),'Timestamped command output replay (1x) | elapsed '+str(second)+'s',font=small,fill='#9aa9be')
 lines=[]
 for e in events:
  if e['seconds']<=second:
   text=f"{e['seconds']:5.1f}s  {e['text']}"
   for line in textwrap.wrap(text,113,subsequent_indent='        '):lines.append(line)
 for i,line in enumerate(lines[-27:]):
  color='#75df9a' if 'HTTP 200' in line else '#ffb886' if 'connection refused' in line else '#e3e8ef'
  d.text((28,168+i*27),line,font=font,fill=color)
 im.save(frames/f'{second:04}.png')
 if second==math.ceil(events[-1]['seconds'])+2:im.save(root/(side+'.png'))
subprocess.run(['ffmpeg','-y','-loglevel','error','-framerate','1','-i',str(frames/'%04d.png'),'-c:v','libx264','-pix_fmt','yuv420p','-r','10','-movflags','+faststart',str(root/(side+'.mp4'))],check=True)
