import json, subprocess, sys
from pathlib import Path
from datetime import datetime
root, out = map(Path, sys.argv[1:])
for side, name in [('base','before'),('head','after')]:
 report=json.loads((root/side/'report.json').read_text())
 attempt=next(r for r in report['run']['results'] if r['attempts'])['attempts'][0]
 steps=attempt['steps']
 epoch=datetime.fromisoformat(attempt['startedAt'])
 def time(step): return (datetime.fromisoformat(step['startedAt'])-epoch).total_seconds()
 first=next(s for s in steps if s['api']=='browser.mouse.wheel')
 send=next(s for s in steps if s['api']=='locator.press')
 done=next(s for s in steps if s['api']=='locator.waitFor' and 'Stop generation' in s.get('label',''))
 start=max(0,time(first)-1)
 stop=time(send)-0.9
 resume=time(done)+done['durationMs']/1000+0.2
 video=root/side/'results'/next(a['path'] for a in attempt['artifacts'] if a['kind']=='video')
 filters=f'[0:v]trim=start={start}:end={stop},setpts=PTS-STARTPTS[a];[0:v]trim=start={resume},setpts=PTS-STARTPTS[b];[a][b]concat=n=2:v=1:a=0[v]'
 subprocess.run(['ffmpeg','-v','error','-i',str(video),'-filter_complex',filters,'-map','[v]','-c:v','libx264','-preset','fast','-crf','19','-pix_fmt','yuv420p','-movflags','+faststart',str(out/f'{name}.mp4')],check=True)
 print(name,{'start':start,'stop':stop,'resume':resume})
