import pathlib,json,subprocess,html,textwrap
root=pathlib.Path(__file__).parent
for side,label in [('base','Before'),('head','After')]:
    directory=root/('run-'+side)
    events=[json.loads(x) for x in (directory/(label+'.cast')).read_text().splitlines()[1:]]
    duration=int(events[-1][0])+3
    for second in range(duration+1):
        lines=['RECORDED SERVER OUTPUT — injected rejection proof','Linux / real Node server / fresh isolated database','Terminal replay from timestamped stdout; no UI capture.','']
        for when,_,message in events:
            if when<=second:
                for line in message.splitlines(): lines.extend(textwrap.wrap(line,105) or [''])
        svg='<svg xmlns="http://www.w3.org/2000/svg" width="1440" height="720"><rect width="1440" height="720" fill="#111827"/>'
        for i,line in enumerate(lines):
            svg+=f'<text x="28" y="{38+i*29}" fill="#e5e7eb" font-family="DejaVu Sans Mono" font-size="20">{html.escape(line)}</text>'
        svg+='</svg>'
        frame=directory/f'frame-{second:04}.png'
        subprocess.run(['convert','svg:-',str(frame)],input=svg,text=True,check=True)
    subprocess.run(['ffmpeg','-y','-loglevel','error','-framerate','1','-i',str(directory/'frame-%04d.png'),'-c:v','libx264','-pix_fmt','yuv420p',str(root/(label+'.mp4'))],check=True)
    subprocess.run(['cp',str(frame),str(root/(label+'.png'))],check=True)
