"""Rebuild cross-stream order, one-to-one scores and mask-overlap links."""
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/r102';U=R/'results/l88';V=R/'results/l89';S=R/'results/l75';p=json.loads((O/'protocol.json').read_text());d=json.loads((O/'results.json').read_text());assert sha(O/'protocol.json')==d['protocol_sha256'] and sha(R/'research/r102_union.py')==d['script_sha256']
for f,h in p['inputs'].items():assert sha(R/f)==h
u=json.loads((U/'results.json').read_text())['records'];v=json.loads((V/'results.json').read_text())['records'];source={(x['pair'],x['condition']):x for x in json.loads((S/'results.json').read_text())['records']};assert len(u)==len(v)==len(d['records'])==16
for row,a,b in zip(d['records'],u,v):
 key=(row['pair'],row['condition']);assert key==(a['pair'],a['condition'])==(b['pair'],b['condition']) and sha(S/row['source_image'])==row['source_image_sha256']==a['source_image_sha256']==b['source_image_sha256'] and sha(U/row['uniform_archive'])==row['uniform_archive_sha256']==a['archive_sha256'] and sha(V/row['variance_archive'])==row['variance_archive_sha256']==b['archive_sha256'] and sha(O/row['panel'])==row['panel_sha256'];streams={}
 for name,folder,case in [('uniform',U,a),('variance',V,b)]:
  z=np.load(folder/case['archive']);shape=tuple(z['mask_shape']);m=np.unpackbits(z['mask_bits'])[:np.prod(shape)].reshape(shape).astype(bool);lookup=dict(zip(z['ids'].tolist(),m));streams[name]=[(name+':'+x,lookup[x]) for x in case['ranking']]
 refs=np.load(U/a['archive'])['refs'];assert np.array_equal(refs,np.load(V/b['archive'])['refs']);ids=source[key]['included_visible_ids'];uu=streams['uniform'];vv=streams['variance'];streams['uniform_first']=[z for i in range(max(len(uu),len(vv))) for z in (uu[i:i+1]+vv[i:i+1])];streams['variance_first']=[z for i in range(max(len(uu),len(vv))) for z in (vv[i:i+1]+uu[i:i+1])]
 for name,items in streams.items():
  assert [x[0] for x in items]==row['rankings'][name]
  for n in (10,30,60,120,'all'):
   selected=items if n=='all' else items[:n];m=np.stack([x[1] for x in selected]) if selected else np.zeros((0,512,512),bool)
   for t in (.5,.75):assert match(refs[ids],ids,m,t)==row['scores'][name][str(n)][str(t)]
 links=[]
 for i,(_,x) in enumerate(uu[:30]):
  for j,(_,y) in enumerate(vv[:30]):
   intersection=int(np.count_nonzero(x&y));union=int(np.count_nonzero(x|y));iou=intersection/union if union else 0
   if iou>=.8:links.append({'uniform_rank':i+1,'variance_rank':j+1,'iou':iou})
 assert links==row['top30_cross_stream_iou08'];print(key,'verified',flush=True)
print('Verified input hashes, stream rankings, scores and overlap links on 16 scenes; matcher shared and no inference rerun.')
