"""Independently verify fixed box audit provenance, NMS and matching."""
import hashlib,itertools,json
from pathlib import Path
import numpy as np
from PIL import Image
from r73_box_audit import labels,starts
ROOT=Path(__file__).resolve().parents[1];OUT=ROOT/'results/r73'
def sha(p):return hashlib.sha256(Path(p).read_bytes()).hexdigest()
def iou(a,b):
 w=max(0,min(a[2],b[2])-max(a[0],b[0]));h=max(0,min(a[3],b[3])-max(a[1],b[1]));inter=w*h;union=(a[2]-a[0])*(a[3]-a[1])+(b[2]-b[0])*(b[3]-b[1])-inter;return inter/union if union else 0.
def nms(items):
 kept=[];aliases=[]
 for q in items:
  hit=next((v for v in kept if iou(q['box'],v['box'])>=.5),None)
  if hit is None:kept.append(q)
  else:aliases.append({'candidate':q['id'],'kept':hit['id']})
 return kept,aliases
def brute(refs,preds,t):
 if len(refs)>4:raise ValueError('Too many reference boxes for independent brute-force check')
 best=0
 for assignment in itertools.product(range(-1,len(preds)),repeat=len(refs)):
  chosen=[j for j in assignment if j>=0]
  if len(chosen)!=len(set(chosen)):continue
  if all(j<0 or iou(refs[i],preds[j])>=t for i,j in enumerate(assignment)):best=max(best,len(chosen))
 return best
def main():
 d=json.loads((OUT/'results.json').read_text());assert d['protocol_sha256']==sha(OUT/'protocol.json');sel=json.loads((OUT/'pair-selection.json').read_text());assert len(sel['pairs'])==len(d['records'])==9
 for rec,row in zip(d['records'],sel['pairs']):
  idx=rec['index'];img=OUT/'sources'/f'{idx:02d}-image.jpg';lab=OUT/'sources'/f'{idx:02d}-label.txt';assert sha(img)==row['image']['sha256'] and sha(lab)==row['label']['sha256'] and Image.open(img).size==(2400,2400) and rec['target_boxes']==labels(lab,2400,2400);assert rec['tile_origins']==[[x,y] for y in starts(2400) for x in starts(2400)]
  for name in ('full','tiled'):
   raw=rec[name+'_raw'];assert all(raw[j]['confidence']>=raw[j+1]['confidence'] for j in range(len(raw)-1));keep,aliases=nms(raw);assert rec[name+'_kept_ids']==[x['id'] for x in keep] and rec[name+'_aliases']==aliases
   for threshold in (.3,.5):assert rec['scores'][name][str(threshold)]['matched']==brute(rec['target_boxes'],[x['box'] for x in keep],threshold)
  for q in rec['tiled_raw']:
   x,y=q['origin'];bb=q['local_box'];assert np.allclose(q['box'],[bb[0]+x,bb[1]+y,bb[2]+x,bb[3]+y],rtol=0,atol=2e-4)
  assert [s['candidate_id'] for s in rec['sam_candidates']]==rec['tiled_kept_ids'][:8]
  for s in rec['sam_candidates']:
   mask=OUT/s['mask'];assert sha(mask)==s['mask_sha256'] and sha(OUT/s['preview'])==s['preview_sha256'];im=np.asarray(Image.open(mask));assert im.shape==(640,640) and set(np.unique(im)).issubset({0,255}) and int((im>0).sum())==s['area']
  assert sha(OUT/rec['image'])==rec['image_sha256']
 print('Verified nine public source pairs, box-coordinate transforms, NMS, independently brute-force box matching and 23 candidate-mask artifacts.')
if __name__=='__main__':main()
