"""Reference-conditioned candidate graph diagnostic; not an automatic tracking algorithm."""
import json
from pathlib import Path
import numpy as np
R=Path(__file__).resolve().parents[1];O=R/'results/r89/opaque';rows=json.loads((O/'results.json').read_text())['records'];out=[]
for r in rows:
 z=np.load(O/r['archive']);m=np.unpackbits(z['mask_bits'])[:int(np.prod(z['mask_shape']))].reshape(z['mask_shape']).astype(bool);by={str(i):(v,int(p)) for i,v,p in zip(z['ids'],m,z['z'])};results=[]
 for source in (0,1):
  nodes={}
  for plane in range(3):
   for ident in r['rankings']['focal']:
    if not ident.startswith('f'+str(plane)+':'):continue
    mask,zidx=by[ident];scores=[]
    for target in range(2):
     ref=z['refs'][zidx,target];u=int((mask|ref).sum());scores.append(int((mask&ref).sum())/u if u else 0)
    labs=[i for i,v in enumerate(scores) if v>=.5]
    if labs==[source]:nodes[ident]=plane
  parent={v:v for v in nodes}
  def root(x):
   while parent[x]!=x:parent[x]=parent[parent[x]];x=parent[x]
   return x
  for edge in r['links']:
   a,b=edge['a'],edge['b']
   if a in nodes and b in nodes:parent[root(a)]=root(b)
  components={}
  for ident,plane in nodes.items():components.setdefault(root(ident),[]).append((ident,plane))
  spans=[len(set(plane for _,plane in vals)) for vals in components.values()];results.append({'source_id':source,'unique_match_candidates_per_plane':[sum(p==z for p in nodes.values()) for z in range(3)],'components':len(components),'component_plane_spans':sorted(spans,reverse=True),'covers_all_three_planes':any(v==3 for v in spans)})
 out.append({'pair':r['pair'],'split':r['split'],'condition':r['condition'],'source_results':results})
(O/'fragmentation-audit.json').write_text(json.dumps({'warning':'Reference-conditioned graph of candidates that uniquely match an underlying synthetic silhouette at IoU 0.5; this is an oracle diagnostic, not a deployable track algorithm.','records':out},indent=2)+'\n');print('sources',len(out)*2,'zero matched candidates',sum(not any(a['unique_match_candidates_per_plane']) for x in out for a in x['source_results']),'all-three-plane components',sum(a['covers_all_three_planes'] for x in out for a in x['source_results']))
