import json, pathlib, re, subprocess, sys
from PIL import Image, ImageDraw
proof_path = pathlib.Path(sys.argv[1])
out = pathlib.Path(sys.argv[2]); out.mkdir(parents=True, exist_ok=True)
proof = json.loads(proof_path.read_text())
manifest = []
for side, tag in [('base', 'before'), ('head', 'after')]:
    data = proof[side]
    for raw in data['captures']:
        source = pathlib.Path(raw)
        if 'failure' in source.name: continue
        label = re.sub(r'^\d+-', '', source.stem)
        dest = out / f'{tag}-{label}.png'
        im = Image.open(source).convert('RGB')
        if 'picker' in label or (side == 'base' and label == 'single-project-new'):
            draw = ImageDraw.Draw(im)
            for y in (190, 238):
                draw.rectangle((390, y, 887, y + 18), fill='#eeeeee')
                draw.text((396, y + 2), 'Workspace path redacted', fill='#666666')
        im.save(dest)
        manifest.append({'label': label, 'side': tag, 'path': str(dest)})
    video = pathlib.Path(data['videos'][0])
    trace = next(video.parents[2].glob('trace.md')).read_text()
    match = re.search(r'app.screenshot` `project-a-filter-viewing-b`.*?video (\d+):(\d+)', trace)
    start = int(match[1]) * 60 + int(match[2])
    dest = out / f'{tag}-scoped-new-interaction.mp4'
    subprocess.run(['ffmpeg', '-y', '-v', 'error', '-ss', str(start), '-i', str(video), '-vf',
        ('drawbox=x=390:y=190:w=498:h=19:color=0xeeeeee:t=fill,drawbox=x=390:y=238:w=498:h=19:color=0xeeeeee:t=fill,' if side == 'base' else '') + 'tpad=stop_mode=clone:stop_duration=2',
        '-t', '6', '-c:v', 'libx264', '-pix_fmt', 'yuv420p', '-movflags', '+faststart', '-an', str(dest)], check=True)
    manifest.append({'label': 'Scoped New interaction (workspace paths redacted)', 'side': tag, 'path': str(dest)})
(out / 'manifest.json').write_text(json.dumps(manifest, indent=2))
