#!/usr/bin/env python3
"""Render timestamped, privacy-filtered live server output as a terminal recording."""
import sys,json,pathlib,textwrap,subprocess
from PIL import Image,ImageDraw,ImageFont
root=pathlib.Path(sys.argv[1]); events=json.loads((root/'events.json').read_text())
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',20)
small=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',18)
width,height=1600,1080; fps=4; duration=events[-1][0]+5
p=subprocess.Popen(['ffmpeg','-y','-f','rawvideo','-pixel_format','rgb24','-video_size',f'{width}x{height}','-framerate',str(fps),'-i','-','-an','-c:v','libx264','-pix_fmt','yuv420p',str(root/'recording.mp4')],stdin=subprocess.PIPE,stderr=subprocess.DEVNULL)
for frame in range(int(duration*fps)+1):
    now=frame/fps; im=Image.new('RGB',(width,height),'#10151c'); d=ImageDraw.Draw(im)
    d.text((30,20),'REAL SERVER OUTPUT | '+root.name.split('-')[0].upper(),font=font,fill='#7dd3fc')
    d.text((30,55),events[1][1],font=small,fill='#d5dce5')
    d.text((30,85),'Linux x86_64 / Node v26.12.1 / isolated fresh state / no client viewport or theme',font=small,fill='#a5b4c5')
    lines=[]
    for t,s in events[4:]:
        if t<=now:
            for l in s.split('\n'):
                lines.extend(textwrap.wrap(l,124,replace_whitespace=False) or [''])
    for i,l in enumerate(lines[-32:]):
        color='#fca5a5' if 'NOT READY' in l or 'CryptoError' in l else '#86efac' if ('READY;' in l or 'unchanged: true' in l or 'after restart: 32' in l) else '#e2e8f0'
        d.text((30,135+i*27),l,font=font,fill=color)
    d.text((30,1030),f'Captured output timeline: {now:05.1f}s | pairing credentials and local paths omitted',font=small,fill='#94a3b8')
    p.stdin.write(im.tobytes())
    if frame==int(duration*fps): im.save(root/'final-frame.png')
p.stdin.close(); assert p.wait()==0
