import json, subprocess, sys
from datetime import datetime
from pathlib import Path
root=Path(sys.argv[1]); output=Path(sys.argv[2])
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]
 video=next(a for a in attempt['artifacts'] if a['kind']=='video')
 origin=datetime.fromisoformat(video['startedAt'].replace('Z','+00:00'))
 offset=lambda s:(datetime.fromisoformat(s['startedAt'].replace('Z','+00:00'))-origin).total_seconds()
 taps=[s for s in attempt['steps'] if s['api']=='locator.tap']
 shots=[s for s in attempt['steps'] if s['api']=='app.screenshot' and s['label'].endswith('-destination')]
 filters=[]
 for i,(tap,shot) in enumerate(zip(taps,shots)):
  start=max(0,offset(tap)-0.5); end=offset(shot)+shot['durationMs']/1000
  filters.append(f'[0:v]trim=start={start}:end={end},setpts=PTS-STARTPTS,tpad=stop_mode=clone:stop_duration=2[v{i}]')
 filters.append('[v0][v1][v2]concat=n=3:v=1:a=0[out]')
 subprocess.run(['ffmpeg','-y','-i',str(root/side/'results'/video['path']),'-filter_complex',';'.join(filters),'-map','[out]','-c:v','libx264','-pix_fmt','yuv420p','-an',str(output/f'{side}-parent-links.mp4')],capture_output=True,check=True)
 subprocess.run(['ffmpeg','-y','-i',str(output/f'{side}-parent-links.mp4'),'-vf','fps=2,scale=640:-1,tile=4x5','-frames:v','1',str(output/f'{side}-excerpts-contact.png')],capture_output=True,check=True)
