#!/usr/bin/env python3
"""Whole-viewport RGB differences: Diff0 marks every >0 channel change; DiffT >16."""
from pathlib import Path
import sys, json
from PIL import Image,ImageChops,ImageDraw
import numpy as np
before,after,out=map(Path,sys.argv[1:4])
out.mkdir(parents=True,exist_ok=True)
a=np.asarray(Image.open(before).convert('RGB')).astype('int16');b=np.asarray(Image.open(after).convert('RGB')).astype('int16')
if a.shape!=b.shape: raise ValueError(f'Viewport mismatch: {a.shape} / {b.shape}')
d=np.abs(a-b);m=d.max(2)
report={}
for threshold,label in [(0,'Diff0'),(16,'DiffT')]:
    mask=m>threshold
    base=(b*.14).astype('uint8')
    base[mask]=[255,40,180]
    Image.fromarray(base).save(out/(label+'.png'))
    ys,xs=np.where(mask)
    report[label]={'threshold':threshold,'changedPixels':int(mask.sum()),'totalPixels':int(mask.size),'bbox':[int(xs.min()),int(ys.min()),int(xs.max()+1),int(ys.max()+1)] if len(xs) else None}
Image.fromarray(np.clip(d*32,0,255).astype('uint8')).save(out/'amplified32.png')
report['amplification']='Diff0 makes every >0 channel change full magenta; amplified32 additionally multiplies absolute RGB differences by 32.'
(out/'metrics.json').write_text(json.dumps(report,indent=2))
labels=['Before','After','Diff0 (>0)','DiffT (>16)']
files=[before,after,out/'Diff0.png',out/'DiffT.png']
w,h=Image.open(before).size
sheet=Image.new('RGB',(w*2,(h+36)*2),'#eeeeee')
draw=ImageDraw.Draw(sheet)
for i,(label,f) in enumerate(zip(labels,files)):
    x=(i%2)*w;y=(i//2)*(h+36)
    draw.text((x+12,y+10),label,fill='black')
    sheet.paste(Image.open(f).convert('RGB'),(x,y+36))
sheet.save(out/'sheet.png')
print(json.dumps(report))
