from pathlib import Path
import subprocess, shutil
from PIL import Image, ImageChops
P=Path(__file__).parent

def run(args): subprocess.run(args,check=True,stdout=subprocess.DEVNULL)
def ff(args): run(['ffmpeg','-y','-hide_banner','-loglevel','error','-threads','2',*args])
def box(x,y,w,h,when=None):
    s=f'drawbox=x={x}:y={y}:w={w}:h={h}:color=black:t=fill'
    return s+(f":enable='{when}'" if when else '')
# Opaque masks cover private filesystem paths, never replace text in filename links.
# The right-side masks cover only environment chrome and an overload toast.
V={
 'base-foreign': [box(300,380,710,30,'lt(t,24)'),box(285,650,710,87,'lt(t,3)')],
 'head-foreign': [box(300,380,710,70,'between(t,8,63)'),box(285,680,710,57,'lt(t,3)')],
 'base-fork': [box(285,620,710,117,'lt(t,3)'),box(300,610,710,40,'between(t,10,22)')],
 'head-fork': [box(285,620,710,117,'lt(t,3)'),box(300,610,710,40,'between(t,15,26)')],
 'base-acp-read': [box(285,650,710,87,'lt(t,3)'),box(300,380,710,30,'between(t,14,23)')],
 'head-acp-read': [box(300,338,710,28,'between(t,24,88)')],
 'base-acp-folder': [],'head-acp-folder': [],
 'base-acp-parent': [box(988,60,292,250),box(888,84,360,140,'lt(t,12)')],
 'head-acp-parent': [box(988,60,292,250),box(888,84,360,140,'lt(t,18)')],
 'head-approved': [box(300,540,710,70,'between(t,15,60)'),box(888,84,360,140,'lt(t,12)')],
}
for name,masks in V.items():
    ff(['-i',str(P/(name+'-raw.mp4')),'-vf',','.join(['scale=1280:800',*masks]),'-c:v','libx264','-threads','2','-preset','veryfast','-crf','23','-an',str(P/(name+'.mp4'))])
    print('prepared',name,flush=True)
# Stable stills from two recorded frames 500 ms apart, cropped identically on each side.
for name,at,crop in [('base-foreign',30,(0,0,1280,640)),('head-foreign',75,(0,0,1280,640)),('base-own',25,(0,0,1280,640)),('head-own',30,(0,0,1280,640)),('base-fork',30,(0,120,1280,620)),('head-fork',35,(0,120,1280,620))]:
    frames=[]
    for index,t in enumerate([at,at+.5]):
        file=P/(name+f'-stable-{index}.png')
        ff(['-ss',str(t),'-i',str(P/(name+'-raw.mp4')),'-vf','scale=1280:800','-frames:v','1',str(file)])
        im=Image.open(file).crop(crop); frames.append(im)
    print(name,'stable crop',ImageChops.difference(*frames).getbbox() is None,flush=True)
    frames[-1].save(P/(name+'-still.png'))
# Normalize actual browser screenshots; these do not change file-name links or output.
for name in ['base-direct','head-direct','base-direct-own','head-direct-own','base-direct-fork','head-direct-fork','base-acp-folder','head-acp-folder-approval','base-acp-parent','head-acp-parent-approval']:
    f=P/(name+'.png')
    if f.exists():
        im=Image.open(f).resize((1280,800))
        im.save(P/(name+'-still.png'))
