#!/usr/bin/env python3
"""Render the timestamped CLI/event recording at 1x speed, without changing its timing."""
import sys,json,pathlib,math,subprocess,textwrap
from PIL import Image,ImageDraw,ImageFont
p=pathlib.Path(sys.argv[1]);records=json.loads((p/'recording.json').read_text()); duration=math.ceil(records[-1]['elapsed'])+3
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',19)
bold=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono-Bold.ttf',23)
W,H=1440,1080
proc=subprocess.Popen(['ffmpeg','-y','-f','rawvideo','-vcodec','rawvideo','-pix_fmt','rgb24','-s',f'{W}x{H}','-r','2','-i','-','-an','-c:v','libx264','-preset','fast','-crf','20','-pix_fmt','yuv420p','-movflags','+faststart',str(p/'recording.mp4')],stdin=subprocess.PIPE,stderr=subprocess.DEVNULL)
def frame(t):
 t=min(t,records[-1]['elapsed'])
 im=Image.new('RGB',(W,H),'#111827');d=ImageDraw.Draw(im)
 d.text((30,24),'Baseline checkpoint | real server + CLI recording',font=bold,fill='#f1f5f9')
 d.text((30,65),f'Elapsed: {t:05.1f}s    |    Playback: 1x    |    No simulated Git delay',font=font,fill='#94a3b8')
 d.line((30,105,W-30,105),fill='#334155',width=2)
 lines=[]
 for r in records:
  if r['elapsed']>t:break
  txt=f"+{r['elapsed']:07.3f}s  {r['text']}"
  color='#86efac' if 'PROVIDER STARTED' in txt else '#f1f5f9'
  if 'waiting for provider' in txt:color='#fcd34d'
  for l in textwrap.wrap(txt,117,subsequent_indent='            '):lines.append((l,color))
 for i,(l,c) in enumerate(lines[-29:]):d.text((30,125+i*29),l,font=font,fill=c)
 d.text((30,H-45),'Recorded CLI requests + read-only persisted application events; synthetic workspace only.',font=font,fill='#94a3b8')
 return im
for n in range(duration*2):proc.stdin.write(frame(n/2).tobytes())
proc.stdin.close();assert proc.wait()==0
frame(duration).save(p/'summary.png')
# Two identical final stills, 500ms apart.
frame(duration+.5).save(p/'summary-stable.png')
