"""Trim authentication-free app videos to the first scripted action; retain raw files."""
from pathlib import Path
import json,subprocess
from PIL import Image,ImageDraw,ImageFont
ROOT=Path('/tmp/lead-25709-r1b/evidence-capture');OUT=ROOT/'videos';OUT.mkdir(exist_ok=True)
RUNS=[ROOT/'2026-10-27T07-37-30-138Z-base-baseline',ROOT/'2026-10-27T07-37-31-442Z-after-off-baseline',ROOT/'2026-10-27T07-39-00-893Z-after-on-feature']
RUNS+=list(ROOT.glob('*-base-baseline-extra'))+list(ROOT.glob('*-after-on-clean-interactions'))+list(ROOT.glob('*-after-on-restricted'))+list(ROOT.glob('*-after-on-scope'))
records=[]
for run in RUNS:
 if run.name=='2026-10-27T07-50-00-080Z-after-on-restricted':continue
 m=json.loads((run/'manifest.json').read_text())
 for c in m['captures']:
  if not c.get('video'):continue
  if '07-39-00' in str(run) and c['name']!='R1-navigation':continue
  f=Path(c['file']);steps=[s for s in m['steps'] if s['recording']==c['name']]
  duration=float(subprocess.check_output(['ffprobe','-v','error','-show_entries','format=duration','-of','csv=p=0',str(f)]))
  if 'stepZeroWall' in c:
   offset=duration-(c['videoEndWall']-c['stepZeroWall'])/1000
  else:
   # The second logged step immediately follows writing the first still.
   first=run/('R1-sidebar-W-L.png' if c['name']=='R1-navigation' else 'sidebar-W-L.png')
   if not first.exists():continue
   stepZero=first.stat().st_mtime-steps[1]['t'];offset=duration-(f.stat().st_mtime-stepZero)
  trim=max(0,offset-.15)+(0.6 if c['name']=='R0-navigation' else 0);dest=OUT/(c['name']+'.mp4')
  subprocess.run(['ffmpeg','-v','error','-y','-ss',str(trim),'-i',str(f),'-an','-c:v','libx264','-crf','18','-preset','fast','-pix_fmt','yuv420p','-movflags','+faststart',str(dest)],check=True)
  timeline=[{'t':round(max(0,s['t']+offset-trim),2),'label':s['label']}for s in steps]
  records.append({'name':c['name'],'file':str(dest),'raw':str(f),'sha':m['sha'],'viewport':c['viewport'],'theme':c.get('theme','light'),'steps':timeline,'trimSeconds':round(trim,3),'timing':'driver wall-clock aligned to video duration; approximately ±0.5 seconds'})
(OUT/'timelines.json').write_text(json.dumps(records,indent=2));print('Prepared',len(records),'videos')
