import os,subprocess,sys
from PIL import Image,ImageDraw
root=sys.argv[1]
for name in ['before-prepare','after-prepare','before-save','after-save']:
 p=root+'/'+name; frames=p+'/frames';os.makedirs(frames,exist_ok=True)
 subprocess.run(['ffmpeg','-y','-i',p+'/interaction.mp4',frames+'/%03d.png'],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,check=True)
 for f in sorted(os.listdir(frames)):
  if not f.endswith('.png'):continue
  im=Image.open(frames+'/'+f).convert('RGB');draw=ImageDraw.Draw(im)
  green=[]
  for y in range(300,600):
   count=sum(1 for r,g,b in [im.getpixel((x,y)) for x in range(287,813)] if g>r+6 and g>b+3)
   if count>100:green.append(y)
  if green:
   top=min(green);draw.rectangle((325,top-57,775,top-24),fill='#d8d8d8')
  else:
   titleRows=[y for y in range(20,220) if sum(1 for x in range(287,550) if max(im.getpixel((x,y)))<130)>25]
   if titleRows:
    pathY=min(titleRows)+(463 if name.startswith('before') else 479)
    draw.rectangle((287,pathY-6,813,pathY+21),fill='#d8d8d8')
  im.crop((262,0,838,780)).save(frames+'/'+f)
 subprocess.run(['ffmpeg','-y','-framerate','10','-i',frames+'/%03d.png','-c:v','libx264','-pix_fmt','yuv420p','-crf','18',p+'/public.mp4'],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,check=True)
 subprocess.run(['ffmpeg','-y','-i',p+'/public.mp4','-vf','fps=2,scale=288:390,tile=5x3','-frames:v','1',p+'/review.png'],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,check=True)
