import json,pathlib,datetime,subprocess,sys
root=pathlib.Path(sys.argv[1]); out=pathlib.Path(sys.argv[2])
def epoch(s): return datetime.datetime.fromisoformat(s.replace('Z','+00:00')).timestamp()
for side in ['base','head']:
 r=json.loads((root/side/'report.json').read_text())['run']
 a=next(x for x in r['results'] if x.get('selected') and x.get('kind')=='test')['attempts'][0]
 origin=epoch(next(x for x in a['artifacts'] if x['kind']=='video')['startedAt'])
 start=next(s for s in a['steps'] if 'Hide file explorer' in s['label'])
 final=[s for s in a['steps'] if s['api']=='app.screenshot'][-1]
 begin=epoch(start['startedAt'])-origin+start['durationMs']/1000
 end=epoch(final['startedAt'])-origin+final['durationMs']/1000
 video=next((root/side/'results').glob('*/attempt-1/video/video.webm'))
 print(side,begin,end,flush=True)
 subprocess.run(['ffmpeg','-y','-i',str(video),'-vf',f'trim=start={begin}:end={end},setpts=8*(PTS-STARTPTS),fps=30','-an','-c:v','libx264','-pix_fmt','yuv420p',str(out/(side+'-interaction-8x-slower.mp4'))],check=True,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
 subprocess.run(['ffmpeg','-y','-i',str(video),'-vf','fps=1/2,scale=320:-1,tile=4x5','-frames:v','1',str(out/(side+'-raw-review.jpg'))],check=True,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
 subprocess.run(['ffmpeg','-y','-i',str(out/(side+'-interaction-8x-slower.mp4')),'-vf','fps=2,scale=426:-1,tile=4x12','-frames:v','1',str(out/(side+'-clip-review.jpg'))],check=True,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
