#!/usr/bin/env python3
"""Render measured request completion timelines, not a browser recording. Requires Pillow and ffmpeg."""
import json,pathlib,sys,subprocess
from PIL import Image,ImageDraw,ImageFont
p=pathlib.Path(sys.argv[1]);data=json.loads(p.read_text());font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',18)
for side in ['before','after']:
 rows=[r for r in data['results'] if r['side']==side]
 proc=subprocess.Popen(['ffmpeg','-y','-loglevel','error','-f','rawvideo','-pixel_format','rgb24','-video_size','1200x700','-framerate','4','-i','-','-c:v','libx264','-pix_fmt','yuv420p',str(p.parent/(side+'-trace.mp4'))],stdin=subprocess.PIPE)
 for frame in range(241):
  t=frame/4;im=Image.new('RGB',(1200,700),'#101820');d=ImageDraw.Draw(im)
  def txt(x,y,s):d.text((x,y),s,font=font,fill='#e7eef5')
  txt(30,20,side.upper()+' '+rows[0]['commit'][:10]+' | measured HTTP request timeline')
  txt(30,55,'Linux, 3-second delayed btrfs, O_APPEND service output, forced writeback every 200 ms')
  txt(30,90,'Playback of raw timings: points appear when responses finish; 3 runs shown together')
  txt(30,125,f'Time {t:05.2f} / 60 seconds | Y: latency 0-6000 ms; X: request start 0-60 s')
  for j,r in enumerate(rows):
   top=195+j*155;txt(30,top,'Run '+str(r['run']));d.line((140,top+110,1140,top+110),fill='#728391');d.line((140,top,140,top+110),fill='#728391')
   visible=[s for s in r['samples'] if s['elapsedSeconds']+s['latencyMs']/1000<=t]
   for s in visible:
    x=140+s['elapsedSeconds']/60*1000;y=top+110-min(6000,s['latencyMs'])/6000*110;d.ellipse((x-2,y-2,x+2,y+2),fill='#ffb088' if side=='before' else '#72dfb7')
   txt(150,top-5,f"completed={len(visible):3}  >1s={sum(s['latencyMs']>1000 for s in visible):2}")
  proc.stdin.write(im.tobytes())
 proc.stdin.close();assert proc.wait()==0
