import json, statistics, subprocess, sys
from datetime import datetime
from pathlib import Path
side = sys.argv[1]
d = json.loads(Path(f'{side}-final-trace.json').read_text())
start = datetime.fromisoformat(d['recordingStarted'].replace('Z','+00:00')).timestamp()*1000
# Media clock after initial buffering, rather than the first playing event.
# The preview screencast paints about 320 ms after its reported start clock;
# verified against the word transitions in the unmodified video frames.
active = [e for e in d['log'] if e.get('highlight') and e.get('audioTime',0)>0.3]
offset = 0.32 + statistics.median(e['time'] + d['epoch'] - e['audioTime']*1000 - start for e in active)/1000
end = (d['log'][-1]['time'] + d['epoch'] - start)/1000 + 0.7
subprocess.run(['ffmpeg','-y','-v','error','-i',f'{side}-final-raw.mp4','-itsoffset',str(offset),'-i',f'{side}-final.mp3','-map','0:v','-map','1:a','-c:v','copy','-c:a','aac','-t',str(end),'-movflags','+faststart',f'{side}-playback.mp4'],check=True)
# Frames from the recording, showing the first visible and / party being spoken.
for name, at in [('and',9),('party',50)]:
    event = next(e for e in d['log'] if e.get('highlight',{} ) and e['highlight']['word']['start']==at)
    t = (event['time'] + d['epoch'] - start)/1000 + 0.42
    subprocess.run(['ffmpeg','-y','-v','error','-ss',str(t),'-i',f'{side}-playback.mp4','-frames:v','1',f'{side}-{name}.png'],check=True)
print(json.dumps({'side':side,'audioOffset':offset,'end':end}))
