"""Reference-conditioned audit of R99 prompt positions and paired outputs."""
import json
from pathlib import Path
import numpy as np
from l70_cellpose import match
from l86_oracle import sha
R=Path(__file__).resolve().parents[1];O=R/'results/l87';S=R/'results/l75';T=R/'results/r99';p=json.loads((O/'protocol.json').read_text())
for f,h in p['inputs'].items():assert sha(R/f)==h
rows=json.loads((T/'results.json').read_text())['records'];records=[]
def iou(a,b):
 inter=int(np.count_nonzero(a&b));union=int(np.count_nonzero(a|b));return inter/union if union else 0.
for r in rows:
 src=S/r['source_archive'];ap=T/r['archive'];assert sha(src)==r['source_archive_sha256'] and sha(ap)==r['archive_sha256'];refs=np.load(src)['refs_visible'];assert not np.any(refs[0]&refs[1]);z=np.load(ap);shape=tuple(z['shape']);masks={n:np.unpackbits(z[n+'_bits'])[:np.prod(shape)].reshape(shape).astype(bool) for n in ('positive','negative')};count=len(r['plans']);assert len(r['directed'])==2*count;items=[]
 for i,v in enumerate(r['directed']):
  ids=[]
  for x,y in (v['positive'],v['negative']):
   hit=[j for j in range(2) if refs[j,y,x]];assert len(hit)<=1;ids.append(hit[0] if hit else None)
  a,b=ids;cat='different' if a is not None and b is not None and a!=b else 'same' if a is not None and a==b else 'one' if (a is None)!=(b is None) else 'neither';scores={n:iou(refs[a],m[i]) if a is not None else None for n,m in masks.items()};items.append({'index':i,'positive_target':a,'negative_target':b,'category':cat,'direct_iou':scores})
 pairs=[]
 for i,plan in enumerate(r['plans']):
  x,y=items[i],items[i+count];informative=x['category']=='different' and y['category']=='different' and x['positive_target']==y['negative_target'] and y['positive_target']==x['negative_target'];out={}
  for name,m in masks.items():
   direct=informative and all(q['direct_iou'][name]>=.5 for q in (x,y));sim=match(refs,[0,1],m[[i,i+count]],.5);out[name]={'both_correct_direct':bool(direct),'one_to_one':sim['matched'],'assignments':sim['assignments']}
  pairs.append({'plan_index':i,'candidate_a':plan['a'],'candidate_b':plan['b'],'informative':informative,'outputs':out})
 records.append({'pair':r['pair'],'condition':r['condition'],'split':r['split'],'source_archive':r['source_archive'],'source_archive_sha256':r['source_archive_sha256'],'r99_archive':r['archive'],'r99_archive_sha256':r['archive_sha256'],'items':items,'pairs':pairs})
 print(r['pair'],r['condition'],'directions',len(items),'informative',sum(x['category']=='different' for x in items),'pairs',sum(x['informative'] for x in pairs),flush=True)
(O/'results.json').write_text(json.dumps({'protocol_sha256':sha(O/'protocol.json'),'script_sha256':sha(__file__),'records':records},indent=2)+'\n')
