from pathlib import Path
import subprocess, json
root = Path('/tmp/lead-32719-r1/capture')
before = root/'2026-11-10T13-01-before'
after = root/'2026-11-10T13-03-after'

def run(args):
    p = subprocess.run(args, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    if p.returncode: raise RuntimeError(p.stderr)
    return p.stdout + p.stderr

out = {}
for side, directory in [('before',before),('after',after)]:
    out[side+'-settled-AE'] = run(['compare','-metric','AE',str(directory/(side+'.png')),str(directory/(side+'-settle-check.png')),'null:']).strip()
    run(['convert',str(directory/(side+'.png')),'-resize','1280x800!',str(root/(side+'.png'))])
    run(['convert',str(directory/(side+'-settle-check.png')),'-resize','1280x800!',str(root/(side+'-settle-check.png'))])
    # Keep the complete browser recording; normalize only pixel size and presentation rate.
    run(['ffmpeg','-y','-i',str(directory/(side+'-raw.mp4')),'-vf','scale=1280:800:flags=lanczos,fps=30','-c:v','libx264','-crf','18','-pix_fmt','yuv420p','-an','-movflags','+faststart',str(root/(side+'.mp4'))])
    out[side+'-video'] = json.loads(run(['ffprobe','-v','error','-show_entries','stream=width,height','-show_entries','format=duration','-of','json',str(root/(side+'.mp4'))]))
# Zero threshold: absolute pixel difference, amplify every nonzero channel to white.
run(['convert',str(root/'before.png'),str(root/'after.png'),'-compose','difference','-composite','-threshold','0',str(root/'diff0.png')])
# Stated threshold: a channel must differ by more than 5% (12.75 / 255).
run(['convert',str(root/'before.png'),str(root/'after.png'),'-compose','difference','-composite','-threshold','5%',str(root/'diff5pct.png')])
(root/'validation.json').write_text(json.dumps(out,indent=2)+'\n')
print(json.dumps(out,indent=2))
