import json, sys, subprocess
from pathlib import Path
from datetime import datetime
root, out = map(Path, sys.argv[1:])
out.mkdir(parents=True, exist_ok=True)
for side in ['base', 'head']:
    report=json.loads((root/side/'report.json').read_text())
    attempt=next(r['attempts'][0] for r in report['run']['results'] if r.get('attempts'))
    start=datetime.fromisoformat(attempt['startedAt'])
    shots=[s for s in attempt['steps'] if s['api']=='app.screenshot' and s['label']!='failure']
    times=[(datetime.fromisoformat(s['startedAt'])-start).total_seconds() for s in shots]
    artifact=next(a for a in attempt['artifacts'] if a['kind']=='video')
    video=root/side/'results'/artifact['path']
    filters=[]
    for i in range(0,len(times),2):
        a=max(0,times[i]-.8)
        b=times[i+1]+.05
        filters.append(f'[0:v]trim=start={a}:end={b},setpts=PTS-STARTPTS,crop=1280:500:0:0,tpad=stop_mode=clone:stop_duration=1[v{i//2}]')
    count=len(times)//2
    filters.append(''.join(f'[v{i}]' for i in range(count))+f'concat=n={count}:v=1:a=0[v]')
    subprocess.run(['ffmpeg','-v','error','-i',str(video),'-filter_complex',';'.join(filters),'-map','[v]','-c:v','libx264','-pix_fmt','yuv420p','-movflags','+faststart',str(out/f'{side}-sends.mp4')],check=True)
