#!/usr/bin/env python3
"""Create full-frame absolute differences and labeled four-panel sheets."""
from pathlib import Path
from PIL import Image,ImageDraw,ImageFont
import numpy as np,json
root=Path('/tmp/lead-27840-r1/capture');p=root/'stills'
font=ImageFont.load_default(size=18)
stats=[]
for before in sorted(p.glob('*-before.png')):
    name=before.name.removesuffix('-before.png');after=p/(name+'-after.png')
    if not after.exists():continue
    a,b=[np.array(Image.open(x).convert('RGB')) for x in [before,after]]
    assert a.shape==b.shape
    delta=np.abs(a.astype(np.int16)-b.astype(np.int16));mask=delta.max(axis=2)>0;threshold=delta.max(axis=2)>16
    diff0=Image.fromarray(np.minimum(delta*32,255).astype('uint8'))
    grey=np.repeat((a.mean(axis=2)*.35).astype('uint8')[:,:,None],3,axis=2)
    grey[threshold]=[255,55,100];diffT=Image.fromarray(grey)
    diff0.save(p/(name+'-diff0.png'));diffT.save(p/(name+'-diffT16.png'))
    h,w=a.shape[:2];sheet=Image.new('RGB',(2*w,2*(h+65)),(28,28,32));draw=ImageDraw.Draw(sheet)
    panels=[(Image.fromarray(a),'Before c6ef3b46eb'),(Image.fromarray(b),'After e9312167e2'),(diff0,'Diff0: absolute RGB x32, zero threshold'),(diffT,'DiffT: max RGB difference >16/255')]
    for i,(im,label) in enumerate(panels):
        x=(i%2)*w;y=(i//2)*(h+65)
        draw.text((x+12,y+8),name,fill='white',font=font);draw.text((x+12,y+33),label,fill='white',font=font);sheet.paste(im,(x,y+65))
    sheet.save(root/(name+'-sheet.png'))
    ys,xs=np.where(mask);bbox=None if not len(xs) else [int(xs.min()),int(ys.min()),int(xs.max()+1),int(ys.max()+1)]
    stats.append(dict(name=name,size=[w,h],pixelsChanged=int(mask.sum()),threshold16Pixels=int(threshold.sum()),bbox=bbox))
(root/'diff-stats.json').write_text(json.dumps(stats,indent=2));print(json.dumps(stats,indent=2))
