import json, pathlib, subprocess
root=pathlib.Path(__file__).parent
out=root/'public'
out.mkdir(exist_ok=True)
mask='drawbox=x=280:y=150:w=400:h=30:color=0xe5e7eb:t=fill,drawbox=x=18:y=828:w=220:h=28:color=0xe5e7eb:t=fill,drawbox=x=1033:y=65:w=180:h=23:color=0xe5e7eb:t=fill'
for side in ['before','after']:
    run=sorted(root.glob(side+'-final-*'))[-1]
    events=json.loads((run/'result.json').read_text())
    safe=[{k:v for k,v in event.items() if k!='text'} for event in events]
    (out/(side+'-actions.json')).write_text(json.dumps(safe,indent=2))
    for name in ['welcome','trailing-slash','slashless-control']:
        subprocess.run(['ffmpeg','-y','-i',str(run/(name+'.png')),'-vf',mask,'-frames:v','1',str(out/(side+'-'+name+'.png'))],check=True,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
    launches=[e for e in events if e['label'].startswith('launch ')]
    a,b=[e['seconds'] for e in launches]
    captions=[(0,a,'Fresh profile - Welcome'),(a,b,'Second instance: https://app.t3.codes/new/?prompt=hi'),(b,999,'Control: https://app.t3.codes/new?prompt=hi')]
    filters=mask+',pad=1280:960:0:0:color=white'
    for i,(start,end,text) in enumerate(captions):
        caption=out/(side+str(i)+'.txt');caption.write_text(text)
        filters+=f",drawtext=textfile={caption}:fontcolor=black:fontsize=22:x=20:y=920:enable='between(t,{start},{end})'"
    subprocess.run(['ffmpeg','-y','-i',str(run/'flow.mp4'),'-vf',filters,'-c:v','libx264','-preset','fast','-crf','22','-pix_fmt','yuv420p','-movflags','+faststart',str(out/(side+'-flow.mp4'))],check=True,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
    for t in [0,4,15,25,33]:
        subprocess.run(['ffmpeg','-y','-ss',str(t),'-i',str(out/(side+'-flow.mp4')),'-frames:v','1',str(out/(side+f'-frame-{t}.jpg'))],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
