import sys, subprocess
from PIL import Image, ImageDraw
from pathlib import Path
root=Path(sys.argv[1]);side=sys.argv[2]
w,h=1080,2424

def redact(im):
    im=im.convert('RGB'); d=ImageDraw.Draw(im)
    # The light confirmation has an opaque white edge here; the alert and page do not.
    confirmation=all(v>240 for v in im.getpixel((150,800))) and all(v<160 for v in im.getpixel((50,800)))
    if confirmation:
        d.rectangle((175,960,911,1460),fill='#e5e5e5')
        d.text((185,1100),'Project and environment details redacted',fill='black')
        d.rectangle((0,1490,119,1800),fill='#e5e5e5')
        d.rectangle((960,1490,1079,1800),fill='#e5e5e5')
        d.rectangle((0,1660,1079,1800),fill='#e5e5e5')
    else:
        d.rectangle((70,1490,1010,1800),fill='#e5e5e5')
        d.text((95,1630),'Connection and filesystem details redacted',fill='black')
    return im
if (root/f'{side}-stable.png').exists():
    redact(Image.open(root/f'{side}-stable.png')).save(root/f'{side}.png')
dec=subprocess.Popen(['ffmpeg','-v','error','-i',str(root/f'{side}-raw.mp4'),'-vf','fps=15','-f','rawvideo','-pix_fmt','rgb24','pipe:1'],stdout=subprocess.PIPE)
enc=subprocess.Popen(['ffmpeg','-v','error','-y','-f','rawvideo','-pix_fmt','rgb24','-s',f'{w}x{h}','-r','15','-i','pipe:0','-an','-c:v','libx264','-preset','fast','-crf','23','-pix_fmt','yuv420p','-movflags','+faststart',str(root/f'{side}.mp4')],stdin=subprocess.PIPE)
count=0
while True:
    data=dec.stdout.read(w*h*3)
    if not data:break
    if len(data)!=w*h*3: raise ValueError('partial frame')
    im=redact(Image.frombytes('RGB',(w,h),data))
    enc.stdin.write(im.tobytes());count+=1
enc.stdin.close(); assert dec.wait()==0;assert enc.wait()==0
print(f'{side}: redacted {count} frames')
