import json,sys,subprocess
from datetime import datetime
from pathlib import Path
root=Path(sys.argv[1]); out=Path(sys.argv[2])
r=json.load(open(root/'report.json'))['run']; a=[r for r in r['results'] if r.get('attempts')][0]['attempts'][0]
v=next(x for x in a['artifacts'] if x['kind']=='video')
dt=lambda s:datetime.fromisoformat(s.replace('Z','+00:00'))
start=next(x for x in a['steps'] if x['api']=='browser.keyboard.type' and x['label']=='56 chars')
last=[x for x in a['steps'] if x['api']=='app.screenshot'][-1]
ss=(dt(start['startedAt'])-dt(v['startedAt'])).total_seconds()-.4
end=(dt(last['startedAt'])-dt(v['startedAt'])).total_seconds()+last['durationMs']/1000
length=min(end-ss,5.5)
print(out.name, 'start',ss,'length',length)
subprocess.run(['ffmpeg','-v','error','-y','-ss',str(ss),'-i',str(root/'results'/v['path']),'-t',str(length),'-an','-c:v','libx264','-crf','18','-pix_fmt','yuv420p',str(out.with_suffix('.trim.mp4'))],check=True)
subprocess.run(['ffmpeg','-v','error','-y','-i',str(out.with_suffix('.trim.mp4')),'-vf','tpad=stop_mode=clone:stop_duration=6','-t','6','-an','-c:v','libx264','-crf','18','-pix_fmt','yuv420p','-movflags','+faststart',str(out)],check=True)
subprocess.run(['ffmpeg','-v','error','-y','-i',str(out),'-vf','fps=5,scale=384:240,tile=5x6','-frames:v','1',str(out.with_suffix('.contact.png'))],check=True)
