"""Redact generated workspace paths; preserve the app's image previews and interactions."""
import json
import subprocess
import sys
from pathlib import Path
from PIL import Image, ImageChops, ImageDraw, ImageStat

proof_dir, output_dir = map(Path, sys.argv[1:])
output_dir.mkdir(parents=True, exist_ok=True)
proof = json.loads((proof_dir / 'proof.json').read_text())
reference = Image.open(next((proof_dir / 'base').rglob('002-acp-image-read.png'))).convert('L')
template = reference.crop((306, 200, 406, 215))

def locate(image):
    gray = image.convert('L')
    choices = [(ImageStat.Stat(ImageChops.difference(gray.crop((306,y,406,y+15)),template)).mean[0], y) for y in range(180, 510)]
    score, y = min(choices)
    return y if score < 5 else None

for side in ('base', 'head'):
    for original in proof[side]['captures']:
        path = Path(original)
        im = Image.open(path).convert('RGB')
        y = locate(im)
        if y is not None:
            draw = ImageDraw.Draw(im)
            draw.rectangle((304,y-2,960,y+37), fill='#fcfcfe')
            draw.text((307,y+5), '[generated workspace path redacted]', fill='#777781')
        im.save(output_dir / f'{side}-{path.name}')
    source = proof[side]['videos'][0]
    # Match the path prefix at every frame; generate only the necessary timed masks.
    decoder = subprocess.Popen(['ffmpeg','-v','error','-i',source,'-vf','fps=25,crop=100:346:306:180,format=gray','-f','rawvideo','-'], stdout=subprocess.PIPE)
    intervals = []
    index = 0
    while True:
        raw = decoder.stdout.read(100*346)
        if len(raw) != 100*346: break
        crop = Image.frombytes('L',(100,346),raw)
        choices = [(ImageStat.Stat(ImageChops.difference(crop.crop((0,y,100,y+15)),template)).mean[0],y+180) for y in range(330)]
        score,y = min(choices)
        if score < 5:
            if intervals and intervals[-1][2] == y and intervals[-1][1] == index:
                intervals[-1][1] = index+1
            else: intervals.append([index,index+1,y])
        index += 1
    decoder.wait()
    filters = [f"drawbox=x=304:y={y-2}:w=656:h=40:color=0xfcfcfe:t=fill:enable='gte(t,{start/25:.3f})*lt(t,{end/25:.3f})'" for start,end,y in intervals]
    print(side, 'mask intervals', intervals, flush=True)
    subprocess.run(['ffmpeg','-y','-v','error','-i',source,'-vf','fps=25,'+','.join(filters) if filters else 'fps=25','-an','-c:v','libx264','-crf','20','-pix_fmt','yuv420p','-movflags','+faststart',str(output_dir/f'{side}-interaction.mp4')],check=True)
