"""Pixel differences of full-viewport captures; no alignment, cropping, or masking."""
from pathlib import Path
from PIL import Image, ImageChops
import json, subprocess, sys
root=Path(sys.argv[1])
rows=sys.argv[2:] or ['U','T-desktop','T-narrow','R','D-final']
metrics=[]
for row in rows:
    before=root/f'{row}-before.png'; after=root/f'{row}-after.png'
    a=Image.open(before).convert('RGB'); b=Image.open(after).convert('RGB')
    if a.size != b.size: raise ValueError((row,a.size,b.size))
    difference=ImageChops.difference(a,b)
    # Max channel difference: one 8-bit level is enough to light a pixel in Diff0.
    maximum=ImageChops.lighter(ImageChops.lighter(difference.getchannel('R'),difference.getchannel('G')),difference.getchannel('B'))
    nonzero=maximum.point(lambda x:255 if x>0 else 0)
    threshold=maximum.point(lambda x:255 if x>5 else 0)
    nonzero.save(root/f'{row}-diff0.png')
    threshold.save(root/f'{row}-diffT.png')
    comparison=subprocess.run(['compare','-metric','AE',str(before),str(after),'null:'],capture_output=True,text=True)
    metrics.append({'pair':row,'size':a.size,'diff0':'max absolute RGB delta > 0, amplified to white','diffT':'max absolute RGB delta > 5/255, amplified to white','changedPixels0':nonzero.histogram()[255],'changedPixelsT':threshold.histogram()[255],'imageMagickAE':comparison.stderr.strip()})
(root/'diff-metrics.json').write_text(json.dumps(metrics,indent=2)+'\n')
print(json.dumps(metrics,indent=2))
