"""Independent source polygon, mask ranking and overlap-score checks for R81."""
import json,hashlib
from pathlib import Path
import cv2,numpy as np
R=Path(__file__).resolve().parents[1];O=R/'results/r81';SRC=Path('/tmp/diatom-r52-pseudo');BIT=np.array([i.bit_count() for i in range(256)],dtype=np.uint8)
def sha(p):return hashlib.sha256(Path(p).read_bytes()).hexdigest()
def main():
 d=json.loads((O/'results.json').read_text());p=json.loads((O/'protocol.json').read_text());special=json.loads((O/'specialist.json').read_text());cp=json.loads((O/'cellpose.json').read_text());assert d['protocol_sha256']==special['protocol_sha256']==cp['protocol_sha256']==sha(O/'protocol.json') and d['specialist_sha256']==sha(O/'specialist.json') and d['cellpose_sha256']==sha(O/'cellpose.json')
 for x in p['inputs']:assert sha(x['path'])==x['sha256']
 audit={r['image_id']:r for r in json.loads((O/'source-audit.json').read_text())['selected']};ss={r['image_id']:r for r in special['records']};cc={r['image_id']:r for r in cp['records']};prior={r['filename']:r for r in json.loads((R/'results/l41/results.json').read_text())['fields']};source_ann={}
 for a in json.loads((SRC/'instances_default.json').read_text())['annotations']:source_ann.setdefault(a['image_id'],[]).append(a)
 checked=0;edges=0
 for r in d['records']:
  ident=r['image_id'];s=ss[ident];c=cc[ident];source=audit[ident];assert sha(O/s['archive'])==s['archive_sha256']==r['specialist_archive_sha256'] and sha(O/c['archive'])==c['archive_sha256']==r['cellpose_archive_sha256'] and sha(O/r['image'])==r['image_sha256'];a=np.load(O/s['archive'],allow_pickle=False);shape=tuple(a['mask_shape']);raw=np.unpackbits(a['mask_bits'])[:int(np.prod(shape))].reshape(shape).astype(bool);refs=list(a['refs']);annids=list(map(int,a['annotation_ids']));assert annids==r['annotation_ids']==[int(x['id']) for x in source_ann[ident]];w,h=source['size_resized'];rebuilt=[]
  for ann in source_ann[ident]:
   mask=np.zeros((h,w),np.uint8)
   for poly in ann['segmentation']:
    q=np.asarray(poly).reshape(-1,2);q[:,0]*=w/source['size_original'][0];q[:,1]*=h/source['size_original'][1];cv2.fillPoly(mask,[np.rint(q).astype('int32')],1)
   rebuilt.append(mask.astype(bool))
  assert len(refs)==len(rebuilt)==source['annotation_count']==r['reference_count'] and all(np.array_equal(x,y) for x,y in zip(refs,rebuilt));overlap=[i for i,m in enumerate(refs) if any(i!=j and np.count_nonzero(m&other)>=10 for j,other in enumerate(refs))];assert overlap==list(a['overlap_indices'])==r['overlap_reference_indices']==source['overlap_reference_indices'];assert len(raw)==s['observed']['candidates']==prior[r['filename']]['scores']['specialist']['candidates'] and len(a['conf'])==len(raw)==len(a['boxes']);b=np.load(O/c['archive'],allow_pickle=False);labels=b['labels'];prob=b['cellprob'];assert labels.shape==prob.shape==(h,w) and np.isfinite(prob).all() and np.isfinite(b['flow']).all();cpids=sorted((int(x) for x in np.unique(labels) if x),key=lambda x:(-float(prob[labels==x].mean()),x));assert [str(x) for x in cpids]==[x['id'] for x in c['ranking']]
  for i,item in zip(cpids,c['ranking']):assert int((labels==i).sum())==item['area'] and abs(float(prob[labels==i].mean())-item['mean_cellprob'])<1e-6
  mask={'yolo:'+str(i):m for i,m in enumerate(raw)};mask.update({'cellpose:'+str(i):labels==i for i in cpids});packed={k:np.packbits(m.ravel()) for k,m in mask.items()};area={k:int(m.sum()) for k,m in mask.items()}
  def iou(x,y):
   inter=int(BIT[packed[x]&packed[y]].sum());u=area[x]+area[y]-inter;return inter/u if u else 0.
  yolo=['yolo:'+str(i) for i in range(len(raw))];cells=['cellpose:'+str(i) for i in cpids]
  def interleave(a,b):
   out=[]
   for j in range(max(len(a),len(b))):
    if j<len(a):out.append(a[j])
    if j<len(b):out.append(b[j])
   return out
  rank={'yolo':yolo,'cellpose':cells,'yolo_first':interleave(yolo,cells),'cp_first':interleave(cells,yolo)}
  for order in ('yolo_first','cp_first'):
   for suffix,thr in (('08',.8),('095',.95)):
    primary=[];deferred=[];links=[]
    for candidate in rank[order]:
     hit=next((x for x in primary if x.split(':',1)[0]!=candidate.split(':',1)[0] and iou(candidate,x)>=thr),None)
     if hit is None:primary.append(candidate)
     else:deferred.append(candidate);links.append({'candidate':candidate,'anchor':hit,'iou':iou(candidate,hit),'semantics':'ranking_deferral_not_identity'})
    key=order+'_'+suffix;rank[key]=primary+deferred;assert set(rank[key])==set(rank[order]) and len(rank[key])==len(rank[order]);assert len(links)==len(r['deferrals'][key])
    for x,y in zip(links,r['deferrals'][key]):assert x['candidate']==y['candidate'] and x['anchor']==y['anchor'] and x['semantics']==y['semantics'] and abs(x['iou']-y['iou'])<1e-12
    edges+=len(links)
  assert rank==r['rankings'];refpacks=[np.packbits(m.ravel()) for m in refs];refareas=[int(m.sum()) for m in refs]
  def tiou(j,candidate):
   inter=int(BIT[refpacks[j]&packed[candidate]].sum());u=refareas[j]+area[candidate]-inter;return inter/u if u else 0.
  def best(refindices,chosen,thr):
   states={0:0.}
   for candidate in chosen:
    vals=[tiou(j,candidate) for j in refindices];nxt=states.copy()
    for bits,total in states.items():
     for k,v in enumerate(vals):
      if not bits&(1<<k) and v>=thr:
       dest=bits|1<<k;nxt[dest]=max(nxt.get(dest,-1.),total+v)
    states=nxt
   bits=max(states,key=lambda x:(x.bit_count(),states[x]));return bits.bit_count(),states[bits]
  for name,ranking in rank.items():
   for budget in (5,10,20,30,'all'):
    chosen=ranking if budget=='all' else ranking[:budget];entry=r['scores'][name][str(budget)]
    for key,thr,indices in [('all05',.5,list(range(len(refs)))),('all075',.75,list(range(len(refs)))),('overlap05',.5,overlap),('overlap075',.75,overlap)]:
     result=entry[key];count,total=best(indices,chosen,thr);assert result['matched']==count==len(result['assignments']) and result['candidate_count']==len(chosen) and result['reference_count']==len(indices) and abs(result['total_iou']-total)<1e-9;seenids=set();seenann=set()
     for a0 in result['assignments']:
      cid=a0['candidate_id'];aid=a0['annotation_id'];j=annids.index(aid);assert cid in chosen and cid not in seenids and aid not in seenann and j in indices and abs(a0['iou']-tiou(j,cid))<1e-9 and a0['iou']>=thr;seenids.add(cid);seenann.add(aid)
    assert entry['near_pairs_iou08']==sum(iou(chosen[i],chosen[j])>=.8 for i in range(len(chosen)) for j in range(i));assignments=entry['all05']['assignments'];pairs=[]
    for j in range(len(assignments)):
     for k in range(j):
      x,y=assignments[j],assignments[k];v=iou(x['candidate_id'],y['candidate_id']);shared=int((refs[annids.index(x['annotation_id'])]&refs[annids.index(y['annotation_id'])]).sum())
      if v>=.8:pairs.append({'candidate_ids':[x['candidate_id'],y['candidate_id']],'annotation_ids':[x['annotation_id'],y['annotation_id']],'prediction_iou':v,'reference_shared_pixels':shared})
    assert len(pairs)==len(entry['matched_near_pairs'])
    for x,y in zip(pairs,entry['matched_near_pairs']):assert x['candidate_ids']==y['candidate_ids'] and x['annotation_ids']==y['annotation_ids'] and x['reference_shared_pixels']==y['reference_shared_pixels'] and abs(x['prediction_iou']-y['prediction_iou'])<1e-12
    checked+=1
  assert r['scores']['yolo']['30']['all05']['matched']==s['observed']['all_05']==prior[r['filename']]['scores']['specialist']['all_05'] and r['scores']['yolo']['30']['all075']['matched']==s['observed']['all_075'] and r['scores']['yolo']['30']['overlap05']['matched']==s['observed']['overlap_subset_05'];print('Verified field',ident,flush=True)
 print('Verified',len(d['records']),'source fields,',edges,'deferral links,',checked,'budget records and source-overlap masks; inference was not rerun.')
if __name__=='__main__':main()
