from pathlib import Path
import subprocess, sys
root=Path(sys.argv[1])
scratch=Path(sys.argv[2])
for side in ['base','head']:
 video=next((root/side/'results').rglob('video.webm'))
 shots=next((root/side/'results').rglob('screenshots'))
 raw=subprocess.check_output(['ffmpeg','-hide_banner','-loglevel','error','-i',str(video),'-vf','fps=10,scale=80:50','-f','rawvideo','-pix_fmt','rgb24','-'])
 frames=[raw[i:i+12000] for i in range(0,len(raw),12000)]
 times=[]
 for name in ['001-pr-checkout-ready.png','002-pr-checkout-complete.png']:
  template=subprocess.check_output(['convert',str(shots/name),'-resize','80x50!','-depth','8','rgb:-'])
  scores=[sum((a-b)*(a-b) for a,b in zip(f,template)) for f in frames]
  idx=min(range(len(scores)),key=scores.__getitem__)
  times.append(idx/10)
 start,end=times
 print(side,'matched ready/complete',times)
 out=scratch/f'{side}-local-checkout.mp4'
 subprocess.run(['ffmpeg','-hide_banner','-loglevel','error','-ss',str(start),'-t',str(end-start+0.1),'-i',str(video),'-vf','tpad=start_mode=clone:start_duration=1:stop_mode=clone:stop_duration=2','-c:v','libx264','-preset','fast','-pix_fmt','yuv420p','-an','-movflags','+faststart',str(out)],check=True)
 subprocess.run(['ffmpeg','-hide_banner','-loglevel','error','-i',str(out),'-vf','fps=2,scale=640:400,tile=3x6','-frames:v','1',str(scratch/f'{side}-local-contact.png')],check=True)
