"""Replay scene selection, exact mask overlaps, reference labels and grouping invariants."""
import json,hashlib,collections
from pathlib import Path
import numpy as np
from l77_association import choose_edges,components,evaluate
R=Path(__file__).resolve().parents[1];O=R/'results/l77';sha=lambda p:hashlib.sha256(Path(p).read_bytes()).hexdigest();data=json.loads((O/'results.json').read_text());p=json.loads((O/'protocol.json').read_text());assert data['protocol_sha256']==sha(O/'protocol.json') and len(data['scenes'])==108;metadata={}
for entry in p['inputs']:
 f=R/entry['path'];assert sha(f)==entry['sha256'];metadata[str(f.parent)]={(x['pair'],x['condition']):x for x in json.loads(f.read_text())['records']}
bitcount=np.array([i.bit_count() for i in range(256)],np.uint8)
for r in data['scenes']:
 old=metadata[r['source']][r['pair'],r['condition']];path=R/r['source']/r['archive'];assert sha(path)==r['archive_sha256']==old['archive_sha256'];z=np.load(path);m=np.unpackbits(z['mask_bits'])[:int(np.prod(z['mask_shape']))].reshape(z['mask_shape']).astype(bool);look={str(k):{'id':str(k),'mask':v,'z':int(plane)} for k,v,plane in zip(z['ids'],m,z['z'])};base=[look[k] for k in old['rankings']['focal'][:30]]
 if r['variant']=='duplicate':nodes=base+[{**v,'id':'copy:'+v['id']} for v in base[:3]]
 elif r['variant']=='missing_middle':nodes=[v for v in base if v['z']!=1]
 else:nodes=base
 assert [{'id':n['id'],'z':n['z']} for n in nodes]==r['nodes'];packs={n['id']:np.packbits(n['mask']) for n in nodes};areas={n['id']:int(n['mask'].sum()) for n in nodes};edges=[]
 for i,a in enumerate(nodes):
  for b in nodes[i+1:]:
   if abs(a['z']-b['z'])!=1:continue
   inter=int(bitcount[np.bitwise_and(packs[a['id']],packs[b['id']])].sum());union=areas[a['id']]+areas[b['id']]-inter;v=inter/union if union else 0.
   if v>=.5:
    lo,hi=(a,b) if a['z']<b['z'] else (b,a);edges.append({'a':lo['id'],'b':hi['id'],'iou':v,'lower_plane':lo['z']})
 assert sorted(edges,key=lambda e:(e['lower_plane'],e['a'],e['b']))==r['possible_edges'];labels={}
 for n in nodes:
  scores=[]
  for j in (0,1):
   ref=z['refs'][n['z'],j];inter=int((n['mask']&ref).sum());u=int((n['mask']|ref).sum());scores.append(inter/u if u else 0.)
  matches=[j for j,v in enumerate(scores) if v>=.5];labels[n['id']]={'class':'unassigned' if not matches else 'ambiguous' if len(matches)>1 else 'unique','source':matches[0] if len(matches)==1 else None,'ious':scores}
 assert labels==r['candidate_labels']
 for name,method in r['methods'].items():
  chosen=choose_edges(r['possible_edges'],name);groups=components(nodes,chosen);assert chosen==method['accepted_edges'] and groups==method['groups'] and evaluate(nodes,groups,chosen,labels)==method['metrics'];assert sorted(v for g in groups for v in g)==sorted(n['id'] for n in nodes)
  if name in ('mutual07','margin'):
   for group in groups:
    zs=[next(n['z'] for n in nodes if n['id']==ident) for ident in group];assert len(zs)==len(set(zs))
assert data['oracle_calibration'][0]['group_count']['mutual07']==1 and data['oracle_calibration'][0]['constructed_source_ids']==[0,1]
print('Verified 108 scene variants, exact possible links, reference-conditioned labels, candidate preservation and grouping constraints; model inference was not rerun.')
# Oracle construction is a separately labeled falsification example, not model inference.
from l77_association import edges_for
orig=next(v for v in json.loads((R/'results/r89/results.json').read_text())['records'] if v['pair']==2 and v['condition']=='crossing_split');arr=np.load(R/'results/r89'/orig['archive']);
for entry in data['oracle_calibration']:
 ids=entry['constructed_source_ids'];nodes=[{'id':'oracle_a','z':0,'mask':arr['refs'][0,ids[0]]},{'id':'oracle_b','z':1,'mask':arr['refs'][1,ids[1]]}];edges=edges_for(nodes);assert (edges[0]['iou'] if edges else None)==entry['edge_iou'];assert {name:len(components(nodes,choose_edges(edges,name))) for name in ('separate','pairwise','components','mutual07','margin')}==entry['group_count']
print('Reconstructed both oracle-generated association calibration cases.')
