"""Posthoc analysis of pre-filter, suppressed, and ranked candidate recall."""
import hashlib,json
from pathlib import Path
import numpy as np
from PIL import Image,ImageDraw
import r58_focal_controls as controls,r44_score_fields as scoring,r38_synthetic_crossings as base
ROOT=Path(__file__).resolve().parents[1];OUT=ROOT/'results/l51'
def sha(p):return hashlib.sha256(Path(p).read_bytes()).hexdigest()
def unpack(a,prefix):
 shape=tuple(int(x) for x in a[prefix+'_shape']);return np.unpackbits(a[prefix+'_bits'])[:np.prod(shape)].reshape(shape).astype(bool)
def main():
 p=json.loads((OUT/'protocol.json').read_text())
 for f in p['inputs']:
  if sha(f['path'])!=f['sha256']:raise ValueError('Frozen input mismatch')
 if (OUT/'results.json').exists():raise FileExistsError('Preserve result')
 source=json.loads((ROOT/'results/r62/results.json').read_text())['records'];records=[]
 for r in source:
  if r['condition'] not in ('crossing_split','crossing_same_middle','crossing_weak'):continue
  a=np.load(ROOT/'results/r62'/r['archive'],allow_pickle=False);refs=list(a['full_masks'].astype(bool));dm=unpack(a,'detector');pm=unpack(a,'point');det=[{'id':str(k),'z':int(z),'mask':m} for k,z,m in zip(a['detector_ids'],a['detector_z'],dm)];pts=[{'id':str(k),'mask':m,'quality':float(q),'area':int(s)} for k,m,q,s in zip(a['point_ids'],pm,a['point_quality'],a['point_area'])];eligible=sorted([x for x in pts if 300<=x['area']<=50000 and x['quality']>=.6],key=lambda x:-x['quality']);raw=det+pts;selected=det+eligible;mapping={x['id']:x for x in raw};rank=[mapping[i] for i in r['scores']['pool_points']['ranking']];assert len(mapping)==len(raw)
  stages={'raw_all':raw,'filtered_unsuppressed':selected,'suppressed_all':rank,'rank_top10':rank[:10]};full_scores={k:scoring.match(refs,v,.5) for k,v in stages.items()};assert full_scores['rank_top10']==r['scores']['pool_points']['budgets']['10'];assert full_scores['suppressed_all']==r['scores']['pool_points']['all']
  # Remove the shared synthetic footprint: this is exclusive geometry, not an optical visibility label.
  exclusive=[refs[0]&~refs[1],refs[1]&~refs[0]];exclusive_scores={k:scoring.match(exclusive,v,.5) for k,v in stages.items()};individual=[];best=[]
  for ref in refs:
   vals=[base.iou(ref,c['mask']) for c in raw];idx=int(np.argmax(vals)) if vals else None
   if idx is None:individual.append({'best_id':None,'best_iou':0});best.append(np.zeros_like(ref))
   else:individual.append({'best_id':raw[idx]['id'],'best_iou':vals[idx]});best.append(raw[idx]['mask'])
  i=len(records)+1;imfile=f'crossing-{i:02d}.jpg';panel=Image.new('RGB',(1200,330),'white');draw=ImageDraw.Draw(panel)
  for col,(title,masks) in enumerate([('Synthetic full targets',refs),('Best raw for target 1',[best[0]]),('Best raw for target 2',[best[1]]),('Mixed top 10',[c['mask'] for c in rank[:10]])]):
   im=Image.fromarray(a['planes'][2]).convert('RGBA');layer=Image.new('RGBA',im.size,(0,0,0,0))
   for j,mask in enumerate(masks):
    c=Image.new('RGBA',im.size,['#00b886','#e85956','#9670df','#e7ba16'][j%4]);c.putalpha(Image.fromarray(mask.astype('uint8')*100));layer=Image.alpha_composite(layer,c)
   panel.paste(Image.alpha_composite(im,layer).convert('RGB').resize((290,290)),(col*300,30));draw.text((col*300+4,5),title,fill='#202a28')
  panel.save(OUT/imfile,quality=85);records.append({'pair':r['pair'],'condition':r['condition'],'source_archive':'/results/r62/'+r['archive'],'image':imfile,'full_scores':full_scores,'exclusive_scores':exclusive_scores,'best_individual_full':individual,'raw_count':len(raw),'filtered_count':len(selected),'retained_count':len(rank),'target_overlap_pixels':r['overlap_pixels']})
  print(f"{i}/9 {r['condition']} pair {r['pair']}: "+' '.join(f"{k}:{v['matched']}/2" for k,v in full_scores.items()),flush=True)
 (OUT/'results.json').write_text(json.dumps({'format':'l51-posthoc-diagnosis-v1','protocol_sha256':sha(OUT/'protocol.json'),'records':records,'warning':'Posthoc use of synthetic targets; best masks are oracle diagnostics, never proposed inference. Exclusive geometry is not verified optical visibility. Previous and current synthetic tests do not establish real-slide or human-level accuracy.'},indent=2)+'\n')
if __name__=='__main__':main()
