import pathlib,subprocess
root=pathlib.Path(__file__).parent
runs=[('before-ts-off-072341','before-tailscale-enable','BEFORE 7e45dcd - Enable Tailscale HTTPS'),('after-ts-off-072926','after-tailscale-enable','AFTER 1d8905a - Enable Tailscale HTTPS'),('before-ts-on-072730','before-tailscale-disable','BEFORE 7e45dcd - Disable Tailscale HTTPS'),('after-ts-on-072821','after-tailscale-disable','AFTER 1d8905a - Disable Tailscale HTTPS')]
def expr(indices):
 intervals=[]
 for n in indices:
  if intervals and intervals[-1][1]==n-1: intervals[-1][1]=n
  else: intervals.append([n,n])
 return '+'.join(f'between(n,{a},{b})' for a,b in intervals) or '0'
for dirname,name,title in runs:
 raw=root/dirname/'raw.mp4'
 pixels=subprocess.check_output(['ffmpeg','-v','error','-i',str(raw),'-vf','crop=300:30:710:200,format=gray','-f','rawvideo','-'])
 counts=[sum(v<130 for v in pixels[i:i+9000]) for i in range(0,len(pixels),9000)]
 # Settings breadcrumb text identifies frames where the unblurred settings page is visible.
 settings=expr([i for i,c in enumerate(counts) if 80<c<2000])
 vf=f"crop=1100:780:410:150,drawbox=x=345:y=105:w=220:h=40:color=0xfafafa:t=fill:enable='{settings}',drawbox=x=325:y=320:w=630:h=45:color=0xfafafa:t=fill:enable='{settings}'"
 if name.endswith('enable'):
  modal=expr([i for i,c in enumerate(counts) if c<80 and 25<i<80])
  vf+=f",drawbox=x=355:y=450:w=400:h=35:color=0xfafafa:t=fill:enable='{modal}'"
 vf+=f",pad=1100:840:0:60:black,drawtext=text='{title}':fontcolor=white:fontsize=24:x=20:y=18"
 dest=root/'public'/(name+'.mp4')
 subprocess.run(['ffmpeg','-y','-v','error','-i',str(raw),'-vf',vf,'-c:v','libx264','-preset','fast','-crf','20','-movflags','+faststart',str(dest)],check=True)
 subprocess.run(['ffmpeg','-y','-v','error','-i',str(dest),'-vf','fps=1/2,scale=550:-1,tile=4x4','-frames:v','1',str(root/'review'/(name+'.png'))],check=True)
