from pathlib import Path
from PIL import Image,ImageChops,ImageDraw
import json
root=Path('/tmp/lead-29548-r1/evidence-capture-2')
rows=[('W1','1440-dark'),('W1','1440-light'),('W1','390-dark'),('W1','390-light'),('W3','1440-dark'),('W2','dismissed'),('W1','390-dark-timeline'),('W1','390-light-timeline'),('M1','android-dark'),('M2','android-dark'),('D1','1440-dark'),('P1','1440-dark')]
stats=[]
for row,variant in rows:
 a=root/f'{row}-before-{variant}.png'; b=root/f'{row}-after-{variant}.png'
 if not a.exists() or not b.exists():continue
 before=Image.open(a).convert('RGB');after=Image.open(b).convert('RGB')
 if before.size!=after.size:raise ValueError((a,b,before.size,after.size))
 delta=ImageChops.difference(before,after)
 channels=delta.split(); maximum=ImageChops.lighter(ImageChops.lighter(channels[0],channels[1]),channels[2])
 details={'row':row,'variant':variant,'pixels':before.width*before.height}
 for threshold,label,color in [(0,'Diff0',(255,0,255)),(16,'DiffT',(255,190,0))]:
  mask=maximum.point(lambda v:255 if v>threshold else 0)
  context=Image.blend(Image.new('RGB',after.size,(40,40,40)),after,0.35)
  context.paste(color,mask=mask)
  context.save(root/f'{row}-{variant}-{label}.png')
  details[label]={'threshold':threshold,'changedPixels':mask.histogram()[255],'boundingBox':mask.getbbox()}
 stats.append(details)
(root/'diff-stats.json').write_text(json.dumps(stats,indent=2))
print(json.dumps(stats,indent=2))
