from PIL import Image, ImageDraw, ImageFont
from pathlib import Path
import json, subprocess, math
root=Path(__file__).parent
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',20)
small=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',16)
for side in ['before','after']:
    folder=Path((root/f'{side}-output.txt').read_text())
    data=json.loads((folder/'recording.json').read_text())
    events=data['events']
    def frame(until):
        im=Image.new('RGB',(1600,1040),'#10151d'); d=ImageDraw.Draw(im)
        d.text((30,18),f'{side.upper()} — Recorded production CLI + HTTP peer output',font=font,fill='#f3f6fa')
        d.text((30,52),'Transcript replay slowed 30x for readability; final frame held 5 seconds.',font=small,fill='#9bacbf')
        y=100
        for event in events:
            if event['at']>until: break
            line=event['line']
            color='#d8e1ec'
            if 'MISSING' in line or 'defect reproduced' in line:color='#ff8989'
            if 'RECEIVED' in line or 'expected behavior' in line:color='#86e0a2'
            if line.startswith('peer ->'):color='#91c5ff'
            d.text((30,y),line,font=font,fill=color); y+=27
        return im
    image=frame(float('inf')); image.save(folder/'capture.png')
    proc=subprocess.Popen(['ffmpeg','-y','-loglevel','error','-f','rawvideo','-pix_fmt','rgb24','-s','1600x1040','-r','10','-i','-','-c:v','libx264','-pix_fmt','yuv420p',str(folder/'recording.mp4')],stdin=subprocess.PIPE)
    duration=events[-1]['at']*30+5
    for n in range(math.ceil(duration*10)):
        proc.stdin.write(frame(n/10/30).tobytes())
    proc.stdin.close()
    if proc.wait()!=0:raise RuntimeError('ffmpeg failed')
    print(side, folder, f'{duration:.1f}s video')
