#!/usr/bin/env python3
"""Export W2 videos after removing startup frames; retain unedited originals privately.
ACP stub harness; no live Antigravity backend.
Usage: media-driver.py beforeA|afterA|beforeB|afterB [raw|excerpt]
"""
import subprocess,pathlib,datetime,json,sys
root=pathlib.Path('/tmp/lead-33596-r2/capture-2');name=sys.argv[1];mode=sys.argv[2] if len(sys.argv)>2 else 'raw'
side='before' if name.startswith('before') else 'after';row='W2a' if name.endswith('A') else 'W2b'
source=root/(name+'-original.private.mp4')
run=root/(name+'-'+mode+'-video-'+datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%S%fZ'));run.mkdir()
metadata=json.loads((root/'recording-metadata.private.json').read_text())[name]
terminal=json.loads((root/(name+'-terminal.json')).read_text())
parse=lambda x:datetime.datetime.fromisoformat(x.replace('Z','+00:00'))
retirement=(parse(terminal['providerTurns'][0]['completedAt'])-parse(metadata['startedAt'])).total_seconds()
probe=json.loads(subprocess.check_output(['ffprobe','-v','error','-show_format','-show_streams','-of','json',str(source)]));duration=float(probe['format']['duration'])
startup=30;endStart=retirement-8;endLength=25
label=(f"scale=1440:900,drawtext=fontfile=/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf:text='{side.upper()} {row} | ACP stub harness; no live Antigravity backend.':x=740:y=14:fontsize=12:fontcolor=white:box=1:boxcolor=black@0.9:boxborderw=3,")
if mode=='raw':
 segments=[('raw',startup,duration-startup)]
 detail='Startup first 30s removed; continuous remainder; real 15-minute watchdog.'
else:
 segments=[('running',startup,22),('retirement',endStart,endLength)]
 detail=f'Startup first 30s removed; idle middle removed (source 30-52s, then {endStart:.3f}s onward).'
label+=f"drawtext=fontfile=/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf:text='{detail}':x=390:y=42:fontsize=12:fontcolor=white:box=1:boxcolor=black@0.9:boxborderw=3"
for segment,start,length in segments:
 vf=label if mode=='raw' else label+',fps=15'
 target=run/(side+'-'+row+'-raw.mp4' if mode=='raw' else segment+'.mp4')
 with open(run/(segment+'-ffmpeg.log'),'w') as log:
  subprocess.run(['ffmpeg','-nostdin','-y','-threads','1','-ss',str(start),'-i',str(source),'-t',str(length),'-filter_threads','1','-vf',vf,'-an','-c:v','libx264','-threads','2','-crf','19','-preset','fast','-pix_fmt','yuv420p','-fps_mode','vfr','-movflags','+faststart',str(target)],stdout=log,stderr=subprocess.STDOUT,check=True)
if mode!='raw':
 (run/'concat.txt').write_text("file 'running.mp4'\nfile 'retirement.mp4'\n")
 subprocess.run(['ffmpeg','-nostdin','-y','-f','concat','-safe','0','-i',str(run/'concat.txt'),'-c','copy','-movflags','+faststart',str(run/(side+'-'+row+'-excerpt.mp4'))],stdout=open(run/'concat.log','w'),stderr=subprocess.STDOUT,check=True)
(run/'source-metadata.json').write_text(json.dumps({'sourceProbe':probe,'recordingStartedAt':metadata['startedAt'],'retirementSourceSeconds':retirement,'startupSecondsRemoved':startup,'retirementSegmentStart':endStart,'retirementSegmentLength':endLength,'segments':segments,'mode':mode,'label':'ACP stub harness; no live Antigravity backend.'},indent=2));print(run)
