#!/usr/bin/env python3
"""Render the driver's timestamped stdout recording, not a browser recording.
Usage: PYTHONPATH=<pillow install> python3 render-recording.py RUN_DIRECTORY
"""
import sys,pathlib,json,subprocess,math
from PIL import Image,ImageDraw,ImageFont
run=pathlib.Path(sys.argv[1]); data=json.loads((run/'summary.json').read_text()); events=data['events']; side=data['side']
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',17)
bold=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono-Bold.ttf',21)
w,h,fps=1440,1000,5; duration=math.ceil(events[-1][0])+10
p=subprocess.Popen(['ffmpeg','-loglevel','error','-y','-f','rawvideo','-pix_fmt','rgb24','-s',f'{w}x{h}','-r',str(fps),'-i','-','-an','-c:v','libx264','-pix_fmt','yuv420p','-crf','20',str(run/(side+'.mp4'))],stdin=subprocess.PIPE)
frames=[]
for frame in range(duration*fps):
    t=frame/fps; im=Image.new('RGB',(w,h),'#101820'); d=ImageDraw.Draw(im)
    d.text((28,20),'BEFORE' if side=='before' else 'AFTER',font=bold,fill='#f0b86c' if side=='before' else '#7fe0aa')
    d.text((165,22),'Real T3 server | timestamped stdout replay | Linux x86_64',font=font,fill='white')
    d.text((28,58),'Commit '+data['commit'],font=font,fill='#b8c9dd')
    d.text((28,87),'Built server + built web assets; fresh synthetic state; same driver; no browser/theme.',font=font,fill='#b8c9dd')
    d.line((28,120,w-28,120),fill='#435268')
    visible=[(ts,s) for ts,s in events if ts<=t]
    for i,(ts,s) in enumerate(visible[-32:]):
        color='#7fe0aa' if s.startswith(('RESULT:','GET /:','HTTP statuses:')) else '#e3e9ef'
        d.text((28,140+i*24),f'{ts:6.2f}s  '+s,font=font,fill=color)
    d.text((28,950),f'Replay {min(t,events[-1][0]):.1f}s / {events[-1][0]:.1f}s | Small-workload structural proof; high-memory stalls unverified.',font=font,fill='#f0b86c')
    p.stdin.write(im.tobytes())
    if frame%fps==0: frames.append(im.copy())
p.stdin.close(); assert p.wait()==0
# Contact sheet showing each second, used to inspect the complete recording.
thumbs=[]
for i,im in enumerate(frames):
    im.thumbnail((576,400)); thumbs.append(im)
contact=Image.new('RGB',(576*3,400*math.ceil(len(thumbs)/3)),'#101820')
for i,im in enumerate(thumbs): contact.paste(im,((i%3)*576,(i//3)*400))
contact.save(run/(side+'-contact.png'))
# Last-frame inspection copy, not a separate still evidence capture.
frames[-1].save(run/(side+'-inspection.png'))
print(run/(side+'.mp4'))
