import sys, json, pathlib, subprocess, datetime, shutil
root=pathlib.Path(sys.argv[1]); scratch=pathlib.Path(sys.argv[2]); out=scratch/'evidence'; out.mkdir(exist_ok=True)
proof=root/'scripts/.e2e/prove'
def stamp(s): return datetime.datetime.fromisoformat(s.replace('Z','+00:00')).timestamp()
def probe(p): return json.loads(subprocess.check_output(['ffprobe','-v','error','-show_entries','format=duration:format_tags=creation_time','-of','json',str(p)]))['format']
summary={}
for side in ['base','head']:
    report=json.loads((proof/side/'report.json').read_text())
    result=next(r for r in report['run']['results'] if r['selected'] and r['attempts'])
    attempt=result['attempts'][0]
    arts=attempt['artifacts']
    native=next(a for a in arts if a['kind']=='video')
    nativepath=proof/side/'results'/native['path']
    start=stamp(native['startedAt'])
    candidates=[]
    for p in scratch.glob('run-*/*.webm'):
        meta=probe(p); created=stamp(meta['tags']['creation_time'])
        if stamp(attempt['startedAt']) <= created <= start:
            candidates.append((created,p))
    created,webpath=max(candidates)
    raw=subprocess.check_output(['ffmpeg','-loglevel','error','-i',str(nativepath),'-vf','crop=700:120:200:150,scale=70:12,fps=10','-f','rawvideo','-pix_fmt','gray','-'])
    first=raw[:840]
    changes=[sum(abs(a-b) for a,b in zip(first,raw[i:i+840]))/840 for i in range(0,len(raw),840)]
    back=next(i/10 for i,v in enumerate(changes) if v>8)
    reopened=next(i/10 for i,v in enumerate(changes) if i/10>back+3 and v<3)
    pixels=subprocess.check_output(['ffmpeg','-loglevel','error','-i',str(webpath),'-vf','crop=2:2:1490:100,fps=10','-f','rawvideo','-pix_fmt','rgb24','-'])
    resize=next(i/10 for i in range(len(pixels)//12) if sum(pixels[i*12:i*12+12])/12<30)
    offset=resize-back-0.6
    duration=min(float(probe(nativepath)['duration']),reopened+2)
    title='Before - base ae837398a2' if side=='base' else 'After - fix 9666abb4a1'
    filt=f"[0:v]scale=390:850,setsar=1,fps=30[m];[1:v]scale=1500:850,setsar=1,fps=30[w];[m][w]hstack=inputs=2,pad=iw:ih+40:0:40:black,drawtext=text='{title} - native mobile (left), web (right)':x=16:y=10:fontcolor=white:fontsize=20[v]"
    subprocess.run(['ffmpeg','-loglevel','error','-y','-i',str(nativepath),'-ss',str(offset),'-i',str(webpath),'-filter_complex',filt,'-map','[v]','-an','-t',str(duration),'-c:v','libx264','-preset','fast','-crf','18','-movflags','+faststart',str(out/f'{side}-back-widen-reopen.mp4')],check=True)
    for a in arts:
        if a['kind']=='screenshot':
            name=pathlib.Path(a['path']).name
            if 'after-back' in name: shutil.copy2(proof/side/'results'/a['path'],out/f'{side}-after-back.png')
            if 'reopened-shell' in name: shutil.copy2(proof/side/'results'/a['path'],out/f'{side}-reopened-shell.png')
    run=webpath.parent
    summary[side]={'attached':(run/'attached-size').read_text().strip(),'afterBack':(run/'after-size').read_text().strip(),'status':result['status'],'webVideoOffset':offset,'duration':duration}
(out/'measurements.json').write_text(json.dumps(summary,indent=2))
print(json.dumps(summary,indent=2))
