from PIL import Image,ImageDraw,ImageFont
from pathlib import Path
import re,subprocess
p=Path(__file__).parent
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',19)
for side,sha in [('base','2c4310eb06'),('head','7aa8b51e95')]:
 lines=(p/f'{side}-run.log').read_text().splitlines()
 # Keep the WebSocket timeline; HTTP keepalive closure is unrelated.
 lines=[x for x in lines if x.startswith('[client')]
 proc=subprocess.Popen(['ffmpeg','-y','-f','rawvideo','-pixel_format','rgb24','-video_size','1280x720','-framerate','1','-i','-','-c:v','libx264','-pix_fmt','yuv420p',str(p/f'{side}-timeline.mp4')],stdin=subprocess.PIPE,stderr=subprocess.DEVNULL)
 for t in range(152):
  im=Image.new('RGB',(1280,720),'#111827');d=ImageDraw.Draw(im)
  d.text((32,24),f'{"BEFORE" if side=="base" else "AFTER"}  {sha}  |  elapsed {t}s',font=font,fill='white')
  d.text((32,65),'Real server runtime transcript replay (1x time)',font=font,fill='#93c5fd')
  d.text((32,99),'Fresh data | silent Node WebSocket | 60s upstream idle proxy',font=font,fill='#cbd5e1')
  y=160
  for line in lines:
   m=re.search(r'\+(\d+\.\d+)s',line)
   if m and float(m[1])<=t:
    d.text((32,y),line,font=font,fill='#fca5a5' if 'closed' in line or 'error' in line else '#86efac');y+=31
  proc.stdin.write(im.tobytes())
 im.save(p/f'{side}-summary.png')
 proc.stdin.close();proc.wait()
