import json, pathlib, subprocess, sys
from datetime import datetime

root = pathlib.Path(sys.argv[1])
out = pathlib.Path(sys.argv[2])
out.mkdir(parents=True, exist_ok=True)
for side in ['base', 'head']:
    report = json.loads((root / side / 'report.json').read_text())
    attempt = next(r for r in report['run']['results'] if r['attempts'])['attempts'][0]
    artifact = next(a for a in attempt['artifacts'] if a['kind'] == 'video')
    video = root / side / 'results' / artifact['path']
    epoch = datetime.fromisoformat(artifact['startedAt'].replace('Z', '+00:00'))
    steps = attempt['steps']
    def offset(step):
        return (datetime.fromisoformat(step['startedAt'].replace('Z', '+00:00')) - epoch).total_seconds()
    def screenshot(label):
        return next(s for s in steps if s['api'] == 'app.screenshot' and s.get('label') == label)
    first_hover = next(s for s in steps if s['api'] == 'locator.hover')
    end_main = screenshot('sent-chip-hover')
    sections = [('main', max(0, offset(first_hover)-0.3), offset(end_main)+end_main['durationMs']/1000+0.15)]
    for name, label in [('warning', 'unreadable-chip-hover'), ('unloaded', 'unloaded-thread-hover')]:
        end = screenshot(label)
        preceding = [s for s in steps if s['api'] == 'locator.hover' and s['index'] < end['index']]
        start = preceding[-1]
        if name == 'warning':
            start = [s for s in steps if s['api'] == 'locator.tap' and 'Run on' in s.get('label', '') and s['index'] < end['index']][-1]
        sections.append((name, max(0, offset(start)-0.3), offset(end)+end['durationMs']/1000+0.15))
    filters=[]
    for i, (_, start, end) in enumerate(sections):
        filters.append(f'[0:v]trim=start={start}:end={end},setpts=PTS-STARTPTS[v{i}]')
    filters.append(''.join(f'[v{i}]' for i in range(len(sections)))+f'concat=n={len(sections)}:v=1:a=0[out]')
    dest=out/f'{side}-hover-interactions.mp4'
    subprocess.run(['ffmpeg','-hide_banner','-loglevel','error','-i',str(video),'-filter_complex',';'.join(filters),'-map','[out]','-c:v','libx264','-threads','2','-crf','20','-pix_fmt','yuv420p','-movflags','+faststart',str(dest)],check=True)
    print(side, sections, dest.name)
