# Usage: python3 render-evidence.py RUN_DIR SIDE SHORT_SHA
import json,sys,subprocess,pathlib
root=pathlib.Path(sys.argv[1]);side=sys.argv[2];sha=sys.argv[3]
def timestamp(t):
    n=round(t*1000);return f'{n//3600000:02}:{n//60000%60:02}:{n//1000%60:02},{n%1000:03}'
stages=json.loads((root/'stages.json').read_text())
(root/'captions.srt').write_text('\n\n'.join(f'{i+1}\n{timestamp(s["start"])} --> {timestamp(s["end"])}\n{s["text"]}' for i,s in enumerate(stages)))
label=f'{side} ({sha}) | Linux X11 | Electron 44.10.1 | window 1600 x 900 | light theme | composer excluded'
font='/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf'
prep=[s for s in stages if s['text'].startswith('Open Thread B') or s['text'].startswith('Reset:')]
mask=','.join(f"drawbox=x=1061:y=40:w=539:h=720:color=0x101827:t=fill:enable='between(t,{s['start']},{s['end']})'" for s in prep)
vf=mask+','+f"pad=1600:866:0:56:color=0x101827,drawtext=fontfile={font}:text='{label}':x=24:y=17:fontsize=20:fontcolor=white"
for i,stage in enumerate(stages):
    caption=root/f'caption-{i}.txt';caption.write_text(stage['text'])
    vf+=f",drawtext=fontfile={font}:textfile={caption}:x=(w-tw)/2:y=832:fontsize=22:fontcolor=white:enable='between(t,{stage['start']},{stage['end']})'"
subprocess.run(['ffmpeg','-y','-i',str(root/'raw.mp4'),'-vf',vf,'-c:v','libx264','-preset','fast','-crf','20','-pix_fmt','yuv420p',str(root/f'{side.lower()}.mp4')],check=True,stdout=subprocess.DEVNULL,stderr=open(root/'render.log','w'))
for name,caption in [('02-after-back','After releasing Back over the iframe'),('05-boundary-after-back','After releasing Back over the iframe with no tab history')]:
    subprocess.run(['convert',str(root/(name+'.png')),'-background','#101827','-gravity','north','-splice','0x56','-gravity','south','-splice','0x50','-font',font,'-fill','white','-pointsize','20','-gravity','northwest','-annotate','+24+16',label,'-gravity','south','-annotate','+0+15',caption,str(root/(side.lower()+'-'+name+'.png'))],check=True)
