"""Keep the same five UI interactions on each side; cut loading, model latency and teardown.
The source is e2e's full, unmodified screen recording. No frames are synthesized or retimed.
"""
import json,sys,subprocess
from pathlib import Path
from datetime import datetime
proof=Path(sys.argv[1]);out=Path(sys.argv[2]);out.mkdir(parents=True,exist_ok=True)
def dt(s):return datetime.fromisoformat(s.replace('Z','+00:00'))
phases=[('silent-full-line-stability-start','restored-full-line'),('output-before-first-text-stability-start','output-dialog'),('subagent-line-stability-start','subagent-action-dialog'),('remote-subagent-line-stability-start','remote-subagent-action-dialog'),('other-now-line-stability-start','other-now-line-narrow')]
for side,label in [('base','before'),('head','after')]:
 report=json.load(open(proof/side/'report.json'));attempt=[r for r in report['run']['results'] if r['attempts']][0]['attempts'][-1]
 video=next(a for a in attempt['artifacts'] if a['kind']=='video');shots={s['label']:s for s in attempt['steps'] if s['api']=='app.screenshot'}
 ranges=[]
 for first,last in phases:
  a=shots[first];b=shots[last];start=max(0,(dt(a['startedAt'])-dt(video['startedAt'])).total_seconds()-.25);end=(dt(b['startedAt'])-dt(video['startedAt'])).total_seconds()+b['durationMs']/1000-.03
  ranges.append((start,end))
 filters=';'.join(f'[0:v]trim=start={start}:end={end},setpts=PTS-STARTPTS[v{i}]' for i,(start,end) in enumerate(ranges))+';'+''.join(f'[v{i}]' for i in range(len(ranges)))+f'concat=n={len(ranges)}:v=1:a=0[out]'
 subprocess.run(['ffmpeg','-hide_banner','-loglevel','error','-i',str(proof/side/'results'/video['path']),'-filter_complex',filters,'-map','[out]','-an','-c:v','libx264','-preset','fast','-crf','20','-pix_fmt','yuv420p',str(out/(label+'.mp4'))],check=True)
 print(label,ranges)
