import json, sys, subprocess
from pathlib import Path
from datetime import datetime

report_dir, output_dir, side = map(Path, sys.argv[1:4])
side = str(side)
report = json.loads((report_dir/'report.json').read_text())
attempt = next(r for r in report['run']['results'] if r['attempts'])['attempts'][-1]
video = next(a for a in attempt['artifacts'] if a['kind']=='video')
source = report_dir/'results'/video['path']
seconds = lambda stamp: datetime.fromisoformat(stamp.replace('Z','+00:00')).timestamp()
origin = seconds(video['startedAt'])
steps = attempt['steps']
fill = next(s for s in steps if s['api']=='locator.fill' and '[data-chat-composer-form]' in s.get('label',''))
last = next(s for s in steps if s['api']=='app.screenshot' and s['label']=='07-send-after-reselect')
start = seconds(fill['startedAt'])-origin-0.1
end = seconds(last['startedAt'])-origin+last['durationMs']/1000
# Remove setup and teardown only. Slow the continuous interaction to one-third speed.
output_dir.mkdir(parents=True,exist_ok=True)
label = 'BEFORE - base 419d9aae29' if side=='base' else 'AFTER - head a5482625f3'
caption = output_dir/f'{side}-caption.txt'
caption.write_text(label+' | Same scenario | 0.33x playback | Scenario = machine A')
video_out = output_dir/('before.mp4' if side=='base' else 'after.mp4')
filters = f"setpts=3*(PTS-STARTPTS),fps=25,pad=iw:ih+60:0:0:color=0x111827,drawtext=fontfile=/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf:textfile={caption}:fontsize=19:fontcolor=white:x=24:y=h-40,tpad=stop_mode=clone:stop_duration=2"
subprocess.run(['ffmpeg','-hide_banner','-loglevel','error','-y','-ss',str(max(start,0)),'-t',str(end-max(start,0)),'-i',str(source),'-vf',filters,'-an','-c:v','libx264','-crf','20','-pix_fmt','yuv420p','-movflags','+faststart',str(video_out)],check=True)
print(json.dumps({'side':side,'trimStart':start,'trimEnd':end,'file':video_out.name}))
