"""Crop recordings to the actual app meter; add environment and command timing labels."""
import json,pathlib,subprocess
root=pathlib.Path(__file__).parent
for side,run,sha in [('base','base-run-2358','d290c1f1b6'),('head','head-run-2359','f8cd5549b0')]:
    ev=json.loads((root/run/'timing.json').read_text())
    labels=[(0,ev[0]['seconds']+.3,'Before commands - large file already read'),(ev[0]['seconds']+.3,ev[1]['seconds']+.3,'Sent /clear'),(ev[1]['seconds']+.3,ev[2]['seconds']+.3,'Sent /context - no normal prompt yet'),(ev[2]['seconds']+.3,40,'Sent normal prompt - fresh API measurement')]
    vf="crop=556:86:1978:460,scale=1112:172,pad=1152:380:20:120:color=white"
    vf+=f",drawtext=text='{side.upper()} {sha} | Web | Chromium | light | 1280x800':x=20:y=20:fontsize=24:fontcolor=black"
    vf+=",drawtext=text='Actual app context meter (privacy crop; continuous real-time recording)':x=20:y=60:fontsize=22:fontcolor=black"
    for a,b,t in labels:
        vf+=f",drawtext=text='{t}':x=20:y=320:fontsize=24:fontcolor=black:enable='between(t,{a},{b})'"
    subprocess.run(['ffmpeg','-y','-i',str(root/f'{side}-final-raw.mp4'),'-t','30','-vf',vf,'-an','-c:v','libx264','-crf','18','-pix_fmt','yuv420p',str(root/f'{side}.mp4')],check=True,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
    subprocess.run(['ffmpeg','-y','-i',str(root/f'{side}.mp4'),'-vf','fps=1/3,tile=2x5','-frames:v','1',str(root/f'{side}-review.png')],check=True,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
