import json, subprocess, sys
from datetime import datetime
from pathlib import Path
out = Path(sys.argv[1])
def time(s): return datetime.fromisoformat(s.replace('Z', '+00:00')).timestamp()
for side in ['base', 'head']:
    folder = Path('scripts/.e2e/prove') / side
    report = json.loads((folder / 'report.json').read_text())
    a = next(r for r in report['run']['results'] if r['attempts'])['attempts'][-1]
    video = next(f for f in a['artifacts'] if f['kind'] == 'video')
    first = next(s for s in a['steps'] if s['api'] == 'locator.tap' and 'Update 1 provider' in s.get('label', ''))
    last = next(s for s in a['steps'] if s['api'] == 'app.screenshot' and s.get('label') == 'different-installation-skipped')
    start = time(first['startedAt']) - time(video['startedAt'])
    duration = time(last['startedAt']) + last['durationMs'] / 1000 + .2 - time(first['startedAt'])
    target = out / f'{side}-update-dialog.mp4'
    subprocess.run(['ffmpeg', '-v', 'error', '-ss', str(start), '-i', str(folder / 'results' / video['path']), '-t', str(duration), '-an', '-c:v', 'libx264', '-preset', 'fast', '-crf', '20', '-pix_fmt', 'yuv420p', '-movflags', '+faststart', str(target)], check=True)
    subprocess.run(['ffmpeg', '-v', 'error', '-i', str(target), '-vf', 'fps=2,scale=480:-1,tile=6x8', '-frames:v', '1', str(out / f'{side}-recording-review.png')], check=True)
    print(side, 'start', start, 'duration', duration)
