from pathlib import Path
from PIL import Image,ImageDraw,ImageFont
import numpy as np,json,datetime
root=Path('/tmp/lead-27882-r1/evidence-capture-1')
out=root/('diffs-'+datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ'));out.mkdir();(root/'diffs-run.txt').write_text(str(out))
def run(side,kind): return Path((root/f'{side}-{kind}-run.txt').read_text().strip())
pairs=[]
for row,kind,names in [('P01','stills',['P01-light','P01-dark']),('P02','stills',['P02-light','P02-dark']),('P03','harness',['P03-dark-390']),('P04','harness',['P04-light-390']),('P05','harness',['P05-dark']),('P06','harness',['P06-light']),('P07','P07',['P07-healthy','P07-failed','P07-returned','P07-recovered']),('P08','P08',['P08-start','P08-returned','P08-recovered']),('P09','harness',['P09-C','P09-B-default','P09-C-returned','P09-C-default'])]:
 for name in names:
  b=run('before',kind)/(name+'.png');a=run('after',kind)/(name+'.png');bi=Image.open(b).convert('RGB');ai=Image.open(a).convert('RGB');assert bi.size==ai.size
  delta=np.abs(np.asarray(ai).astype(np.int16)-np.asarray(bi).astype(np.int16));mask=delta.max(axis=2)>0;maskt=delta.max(axis=2)>16
  d0=out/(name+'-Diff0.png');dt=out/(name+'-DiffT.png');Image.fromarray(np.minimum(delta*16,255).astype('uint8')).save(d0)
  arr=np.zeros_like(np.asarray(bi));arr[maskt]=[255,0,255];Image.fromarray(arr).save(dt)
  coords=np.argwhere(mask);box=None if not mask.any() else [int(coords[:,1].min()),int(coords[:,0].min()),int(coords[:,1].max()+1),int(coords[:,0].max()+1)]
  pairs.append(dict(row=row,name=name,before=str(b),after=str(a),diff0=str(d0),diffT=str(dt),width=bi.width,height=bi.height,changedPixels0=int(mask.sum()),changedPixels16=int(maskt.sum()),bbox0=box))
font=ImageFont.truetype('/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf',18)
for row in dict.fromkeys(p['row'] for p in pairs):
 rp=[p for p in pairs if p['row']==row];width=2880;heights=[int(p['height']*720/p['width'])+66 for p in rp];sheet=Image.new('RGB',(width,sum(heights)), '#f0f0f0');d=ImageDraw.Draw(sheet);y=0
 for p,h in zip(rp,heights):
  for col,key,label in [(0,'before','Before cb9629e689'),(1,'after','After c60e8ba864'),(2,'diff0','Diff0 | abs RGB x16 | threshold 0'),(3,'diffT','DiffT | max channel >16/255')]:
   d.text((col*720+10,y+6),p['name']+' | '+label,font=font,fill='black');im=Image.open(p[key]);im=im.resize((720,h-66),Image.Resampling.LANCZOS);sheet.paste(im,(col*720,y+46))
  y+=h
 sheet.save(out/(row+'-sheet.png'))
(root/'pairs.json').write_text(json.dumps(pairs,indent=2))
print(out)
