from pathlib import Path
from PIL import Image, ImageDraw, ImageFont
import numpy as np, json
p=Path(__file__).parent
stats={}
for row in ['M1-dark','M2-dark','M3-dark','key-light','O3']:
 a_path=Path('/tmp/issue-lead-33369-r2/evidence-capture-1')/f'before-{row}.png'; b_path=p/f'after-{row}.png'
 if not a_path.exists() or not b_path.exists(): continue
 a=np.asarray(Image.open(a_path).convert('RGB')).astype('int16');b=np.asarray(Image.open(b_path).convert('RGB')).astype('int16')
 assert a.shape==b.shape,(row,a.shape,b.shape)
 delta=np.abs(a-b); magnitude=delta.max(axis=2)
 # Zero threshold: each nonzero channel difference is multiplied by 32, then clipped.
 d0=np.clip(delta*32,0,255).astype('uint8')
 # Threshold 16/255 in the maximum RGB channel; magenta on dimmed baseline context.
 dt=(a*0.30).astype('uint8');dt[magnitude>16]=[255,0,160]
 Image.fromarray(d0).save(p/f'{row}-diff0.png')
 Image.fromarray(dt).save(p/f'{row}-diffT16.png')
 ys,xs=np.nonzero(magnitude)
 stats[row]={'changedPixels':int((magnitude>0).sum()),'threshold16Pixels':int((magnitude>16).sum()),'bbox':[int(xs.min()),int(ys.min()),int(xs.max()+1),int(ys.max()+1)] if len(xs) else None}
 width,height=a.shape[1],a.shape[0]
 sheet=Image.new('RGB',(width*2,(height+58)*2),'#17171a');draw=ImageDraw.Draw(sheet)
 font=ImageFont.load_default(size=20)
 for i,(name,file) in enumerate([('Before · b8c2cfad6b',a_path),('After · 0148848580',b_path),('Diff0 · absolute RGB x32 · zero threshold',p/f'{row}-diff0.png'),('DiffT · max RGB >16/255 · magenta',p/f'{row}-diffT16.png')]):
  x=(i%2)*width;y=(i//2)*(height+58)
  draw.text((x+16,y+16),name,fill='white',font=font)
  sheet.paste(Image.open(file).convert('RGB'),(x,y+58))
 sheet.save(p/f'{row}-sheet.png')
print(json.dumps(stats,indent=2));(p/'pixel-stats.json').write_text(json.dumps(stats,indent=2))
