# Render timestamped output captured by driver.cjs; preserve request timing.
import json,pathlib,subprocess
root=pathlib.Path(__file__).parent
for side in ['base','head']:
    run=sorted((root/side).glob('*/recording.json'))[-1]
    events=json.loads(run.read_text())
    cast={'version':2,'width':110,'height':26,'timestamp':0,'title':side.upper()+' real server RPC recording','env':{'TERM':'xterm-256color'}}
    with (root/(side+'.cast')).open('w') as f:
        f.write(json.dumps(cast)+'\n')
        for t,line in events:f.write(json.dumps([t,'o',line+'\r\n'])+'\n')
    frames=root/(side+'-frames');frames.mkdir()
    concat=[]
    for i,(t,line) in enumerate(events):
        text='TIMESTAMPED REAL SERVER RPC OUTPUT\n\n'+'\n'.join(x[1] for x in events[:i+1])
        frame=frames/(str(i)+'.png')
        subprocess.run(['convert','-size','1280x720','xc:#101820','-font','DejaVu-Sans-Mono','-pointsize','17','-fill','#e5edf5','-interline-spacing','10','-annotate','+28+42',text,str(frame)],check=True)
        duration=max(.08,events[i+1][0]-t) if i+1<len(events) else 5
        concat.extend(["file '"+str(frame)+"'",'duration '+str(duration)])
    concat.append("file '"+str(frame)+"'")
    (frames/'concat.txt').write_text('\n'.join(concat))
    subprocess.run(['ffmpeg','-y','-loglevel','error','-f','concat','-safe','0','-i',str(frames/'concat.txt'),'-vf','fps=10','-c:v','libx264','-pix_fmt','yuv420p','-movflags','+faststart',str(root/(side+'.mp4'))],check=True)
