from pathlib import Path
from PIL import Image,ImageDraw,ImageFont
import subprocess,time,re,sys,textwrap
root=Path(__file__).parent
side=sys.argv[1];run=Path((root/(side+'-run')).read_text())
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',18)
large=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',26)
p=subprocess.Popen(['ffmpeg','-y','-loglevel','error','-f','rawvideo','-pixel_format','rgb24','-video_size','1280x800','-framerate','1','-i','-','-c:v','libx264','-preset','ultrafast','-crf','23','-pix_fmt','yuv420p',str(root/(side+'.mp4'))],stdin=subprocess.PIPE)
end=None
while True:
 im=Image.new('RGB',(1280,800),'#10151e');d=ImageDraw.Draw(im)
 d.text((30,24),f'{side.upper()} | T3 Connect headless login',font=large,fill='white')
 sha='11e5b13f38' if side=='before' else '46da932268'
 d.text((30,65),f'Commit {sha} | Linux / Node | test stage | fresh isolated home',font=font,fill='#b4c2d4')
 d.text((30,94),'Live recording of CLI stdout + fault-proxy events (1 frame/sec)',font=font,fill='#b4c2d4')
 raw=(run/'events.log').read_text();lines=[]
 for l in raw.splitlines():
  if re.match(r'^\+\d',l) and not any(x in l for x in ['migrations','Migrations','INFO']):
   lines.extend(textwrap.wrap(l,108) or [''])
 for i,l in enumerate(lines[-23:]):
  color='#ffb86b' if 'HOLD' in l or 'Timeout' in l or 'EXIT 1' in l else '#7de3af' if 'Signed in' in l or 'EXIT 0' in l else '#d9e1eb'
  d.text((30,145+i*26),l,font=font,fill=color)
 p.stdin.write(im.tobytes())
 if (run/'exit').exists():
  im.save(root/(side+'.png'))
  if end is None:end=time.monotonic()+3
  if time.monotonic()>end:break
 time.sleep(1)
p.stdin.close();p.wait()
