import re,subprocess,json
from datetime import datetime
from pathlib import Path
root=Path(__file__).parent
for group in ['web-final-proof','gitlab-proof','gitlab-issue-proof','mobile-proof']:
 if not (root/group).exists():continue
 for side in ['base','head']:
  sidepath=root/group/side
  traces=list(sidepath.glob('results/*/trace.md'))
  if not traces:continue
  trace=traces[0].read_text()
  times=[]
  for line in trace.splitlines():
   if '✓ `app.screenshot`' not in line:continue
   match=re.search(r'video (\d+):(\d+)',line)
   if match:times.append(int(match[1])*60+int(match[2]))
  video=next(p for p in sidepath.glob('results/*/attempt-1/video/*') if p.suffix in ['.mp4','.webm'])
  if not times:
   metadata=json.loads(subprocess.check_output(['ffprobe','-v','error','-show_entries','format=duration:format_tags=creation_time','-of','json',str(video)],text=True))['format']
   end_stamp=datetime.fromisoformat(metadata['tags']['creation_time'].replace('Z','+00:00')).timestamp()
   video_start=end_stamp-float(metadata['duration'])
   report=json.loads((sidepath/'report.json').read_text())
   attempt=next(x for x in report['run']['results'] if x['attempts'])['attempts'][0]
   times=[int(datetime.fromisoformat(step['startedAt'].replace('Z','+00:00')).timestamp()-video_start) for step in attempt['steps'] if step['api']=='app.screenshot']
  if not times:continue
  start=max(0,times[0]-2)
  end=times[-1]+3
  out=root/f'{group.removesuffix("-proof")}-{side}.mp4'
  subprocess.run(['ffmpeg','-y','-ss',str(start),'-i',str(video),'-t',str(end-start),'-c:v','libx264','-preset','fast','-crf','20','-pix_fmt','yuv420p','-an','-map_metadata','-1',str(out)],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,check=True)
  print(out.name,'source interval',start,end)
