import pathlib,re,subprocess,sys
root=pathlib.Path('scripts/.e2e/prove')
out=pathlib.Path(sys.argv[1])
for side,label in [('base','before'),('head','after')]:
    trace=next((root/side/'results').glob('*/trace.md'))
    text=trace.read_text()
    def time_for(api):
        line=next(s for s in text.splitlines() if api in s and 'video ' in s)
        m=re.search(r'video (\d+):(\d+)',line)
        return int(m[1])*60+int(m[2])
    start=time_for('browser.waitForResponse')-1
    end=time_for('Toggle terminal drawer')-0.1
    video=trace.parent/'attempt-1/video/video.webm'
    still=trace.parent/'attempt-1/screenshots/001-invoice-sidecar.png'
    # Omit pairing and the shell startup prompt; append the unchanged terminal screenshot.
    subprocess.run(['ffmpeg','-hide_banner','-loglevel','error','-ss',str(start),'-t',str(end-start),'-i',str(video),'-loop','1','-t','4','-i',str(still),'-filter_complex','[0:v]fps=30,setsar=1,setpts=PTS-STARTPTS[v0];[1:v]fps=30,setsar=1,setpts=PTS-STARTPTS[v1];[v0][v1]concat=n=2:v=1:a=0,format=yuv420p[v]','-map','[v]','-c:v','libx264','-crf','18','-movflags','+faststart',str(out/f'{label}.mp4')],check=True)
