import json,subprocess,sys
from pathlib import Path
from datetime import datetime
scratch=Path(sys.argv[2])
runner=Path(sys.argv[1])
metadata=[]
for side,rel in [('before','.e2e/manual-base'),('after','.e2e/prove/head')]:
 root=runner/rel
 report=json.load(open(root/'report.json'))['run']
 attempt=next(x for x in report['results'] if x.get('attempts'))['attempts'][0]
 video=next(x for x in attempt['artifacts'] if x['kind']=='video')
 origin=datetime.fromisoformat(video['startedAt'])
 def offset(s):return (datetime.fromisoformat(s['startedAt'])-origin).total_seconds()
 steps=attempt['steps']
 home=next(x for x in steps if x['api']=='app.screenshot' and x['label']=='home-projects-and-threads')
 newchat=next(x for x in steps if x['api']=='locator.tap' and 'New chat' in x['label'])
 context=next(x for x in steps if x['api']=='app.screenshot' and x['label']=='project-a-new-task-draft-context')
 last=next(x for x in steps if x['api']=='app.screenshot' and x['label']=='project-a-new-task-draft-model-search')
 begin, end, mask_start, mask_end, draft_raw = {
  "before": (95.5,279.0,234.0,240.0,224.5),
  "after": (71.572,248.167,209.0,213.5,200.0),
 }[side]
 
 src=root/'results'/video['path']
 enable=f"between(t,{mask_start},{mask_end})"
 vf=f"scale=804:1748,drawbox=x=0:y=316:w=iw:h=44:color=0xf3f3f8:t=fill:enable='{enable}',drawbox=x=0:y=448:w=iw:h=44:color=0xf3f3f8:t=fill:enable='{enable}',trim=start={begin}:end={end},setpts=PTS-STARTPTS"
 dest=scratch/f'ios-{side}-full.mp4'
 subprocess.run(['ffmpeg','-y','-loglevel','error','-i',str(src),'-vf',vf,'-an','-c:v','libx264','-preset','veryfast','-crf','22','-threads','2','-movflags','+faststart',str(dest)],check=True)
 draft_start=draft_raw-begin
 subprocess.run(['ffmpeg','-y','-loglevel','error','-ss',str(draft_start),'-i',str(dest),'-an','-c:v','libx264','-preset','veryfast','-crf','22','-threads','2','-movflags','+faststart',str(scratch/f'ios-{side}-draft.mp4')],check=True)
 metadata.append({'side':side,'status':attempt['status'],'start':begin,'end':end,'duration':end-begin,'draftStartInFull':draft_start,'maskStartInFull':mask_start-begin,'maskEndInFull':mask_end-begin})
(scratch/'ios-video-timing.json').write_text(json.dumps(metadata,indent=2))
