#!/usr/bin/env python3
"""Render recorded stdout events at their original timestamps, without changing observations."""
import json, pathlib, subprocess, sys
root=pathlib.Path(sys.argv[1])
for side in ['before','after']:
    data=json.loads((root/(side+'.json')).read_text())
    lines=[(0,'T3 CODE | REAL SERVER SHUTDOWN'),(0,'Recorded command output - replayed at original timing')]+[(t,f'{t:7.3f}s  {m}') for t,m in data['events']]
    filters=[]
    for i,(t,line) in enumerate(lines):
        f=root/f'{side}-line-{i}.txt';f.write_text(line)
        color='white' if i<2 else ('0xfca5a5' if side=='before' else '0x86efac')
        filters.append(f"drawtext=fontfile=/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf:textfile={f}:fontsize=20:fontcolor={color}:x=32:y={32+i*34}:enable='gte(t,{t})'")
    subprocess.run(['ffmpeg','-hide_banner','-loglevel','error','-f','lavfi','-i','color=c=0x111827:s=1440x900:r=10:d=12','-vf',','.join(filters),'-c:v','libx264','-pix_fmt','yuv420p','-y',str(root/(side+'.mp4'))],check=True)
    subprocess.run(['ffmpeg','-hide_banner','-loglevel','error','-ss','11','-i',str(root/(side+'.mp4')),'-frames:v','1','-y',str(root/(side+'.png'))],check=True)
