from pathlib import Path
import subprocess
from PIL import Image, ImageDraw, ImageChops
root=Path(__file__).parent
for side in ('base','head'):
 for flow in ('create','add'):
  raw=root/(('' if flow=='create' else 'add-')+side+'-raw.mov')
  masks=[]
  if flow=='create':
   for x,y,w,h in [(515,347,480,22),(473,431,490,22)]:
    enable='' if side=='base' else ":enable='lte(t,4)'"
    masks.append(f'drawbox=x={x}:y={y}:w={w}:h={h}:color=0xd0d0d0:t=fill'+enable)
  else:
   masks.append('drawbox=x=473:y=278:w=435:h=28:color=0xd0d0d0:t=fill')
   masks.append("drawbox=x=473:y=385:w=400:h=30:color=0xd0d0d0:t=fill:enable='lte(t,1.5)'")
  masks += ['drawbox=x=1190:y=156:w=135:h=28:color=0xd0d0d0:t=fill', 'drawbox=x=1060:y=200:w=345:h=45:color=0xd0d0d0:t=fill']
  label=f"{'Before' if side=='base' else 'After'} | Safari 26.6.2 | {'Create project' if flow=='create' else 'Add existing folder'} | private paths masked"
  filters=['trim=start=10:end=25','setpts=PTS-STARTPTS',*masks,'crop=1440:670:0:140','pad=1440:720:0:50:color=0x202020',f"drawtext=text='{label}':fontcolor=white:fontsize=22:x=24:y=14"]
  subprocess.run(['ffmpeg','-v','error','-y','-i',str(raw),'-vf',','.join(filters),'-an','-c:v','libx264','-crf','20','-pix_fmt','yuv420p','-movflags','+faststart',str(root/f'{flow}-{side}.mp4')],check=True)
for flow in ('create','add'):
 for side in ('base','head'):
  prefix=side if flow=='create' else 'add-'+side
  if flow=='create' and side=='head': prefix='head-clean'
  a=Image.open(root/(prefix+'-1.png' if prefix=='head-clean' else prefix+'-final-1.png')).convert('RGB')
  b=Image.open(root/(prefix+'-2.png' if prefix=='head-clean' else prefix+'-final-2.png')).convert('RGB')
  print(flow,side,'stable pair difference:',ImageChops.difference(a,b).getbbox())
  d=ImageDraw.Draw(a)
  if side=='base' and flow=='create':
   d.rectangle((515,347,995,369),fill='#d0d0d0');d.rectangle((473,431,963,453),fill='#d0d0d0')
  if side=='base' and flow=='add':d.rectangle((473,278,908,306),fill='#d0d0d0')
  d.rectangle((1190,156,1325,184),fill='#d0d0d0')
  a.crop((0,140,1440,810)).save(root/f'{flow}-{side}.png')
