"""Preserve R72 source masks and explicit, non-biological suppression links."""
import hashlib,json
from pathlib import Path
import numpy as np
from PIL import Image
from diatom_pilot.fast_mask_nms import greedy_mask_nms
from diatom_pilot.proposal_graph import build_graph,pack_candidates,unpack_candidates,mask_digest
ROOT=Path(__file__).resolve().parents[1]; OUT=ROOT/'results/l63'
def sha(p):return hashlib.sha256(p.read_bytes()).hexdigest()
def load(path):return json.loads(path.read_text())
def decode(a):
 shape=tuple(a['candidate_shape']);return np.unpackbits(a['candidate_bits'])[:int(np.prod(shape))].reshape(shape).astype(bool)
def main():
 OUT.mkdir(parents=True,exist_ok=True)
 inputs=[ROOT/'results/l60/results.json',ROOT/'results/r72/results.json',ROOT/'results/r72/inspector-planes.json',ROOT/'results/r65/native-crops.npz',Path(__file__),ROOT/'diatom_pilot/proposal_graph.py',ROOT/'diatom_pilot/fast_mask_nms.py']+[ROOT/f'results/{s}/field-{i:02}.npz' for s in ('l60','r72') for i in range(1,4)]
 protocol={'format':'l63-protocol-v1','description':'Reconstruct L60 initial suppression, preserve all L60 and R72 raw masks and recorded suppression links. No new predictions or labels.','inputs':[{ 'path':str(p.relative_to(ROOT)),'sha256':sha(p)} for p in inputs],'nms_iou_threshold':0.8,'caveat':'Relations indicate algorithmic suppression only; no identity inference.'}
 (OUT/'protocol.json').write_text(json.dumps(protocol,indent=2)+'\n')
 l60=load(ROOT/'results/l60/results.json')['records'];r72=load(ROOT/'results/r72/results.json')['records'];planes=load(ROOT/'results/r72/inspector-planes.json')['fields'];crops=np.load(ROOT/'results/r65/native-crops.npz',allow_pickle=False);summaries=[]
 for i,(old,rec,plane_info) in enumerate(zip(l60,r72,planes),1):
  assert old['field']==rec['field']==plane_info['field']; field=f'field-{i:02}';dest=OUT/field;dest.mkdir(exist_ok=True);candidates=[]
  for p in plane_info['planes']:
   path=ROOT/'results/r72'/p['path'];assert sha(path)==p['sha256'];assert np.array_equal(np.asarray(Image.open(path)),crops[old['field']][p['z']])
  a=np.load(ROOT/'results/l60'/old['archive'],allow_pickle=False);m=decode(a); assert sha(ROOT/'results/l60'/old['archive'])==old['archive_sha256']
  detmeta={ident:{'box_xyxy':box,'detector_confidence':conf} for per in old['per_plane'] for ident,box,conf in zip(per['candidate_ids'],per['boxes'],per['detector_confidence'])}
  for ident,z,mode,mask in zip(a['candidate_ids'],a['candidate_z'],a['candidate_mode'],m):
   ident=str(ident);candidates.append({'id':ident,'z':int(z),'source':str(mode),'mask':mask,'metadata':detmeta[ident]})
  a=np.load(ROOT/f'results/r72/{field}.npz',allow_pickle=False);m=decode(a)
  for j,mask in enumerate(m):
   kind=str(a['kind'][j]); meta={'quality':float(a['quality'][j]),'prompt':a['xyxy'][j].tolist() if kind=='box' else a['xy'][j].tolist(),'prompt_type':kind}
   if kind=='box':meta['contrast']=float(a['contrast'][j])
   assert int(mask.sum())==int(a['area'][j]);candidates.append({'id':str(a['ids'][j]),'z':int(a['z'][j]),'source':kind,'mask':mask,'metadata':meta})
  byid={c['id']:c for c in candidates}; assert len(byid)==len(candidates)
  relations=[]
  def add(stage,aliases):relations.extend({'stage':stage,**x} for x in aliases)
  for mode in ('original','clahe'):
   per=[[byid[x] for x in next(row for row in old['per_plane'] if row['mode']==mode and row['z']==z)['candidate_ids']] for z in range(5)]
   stream=[per[z][j] for j in range(max(map(len,per))) for z in (2,1,3,0,4) if j<len(per[z])]
   keep,aliases=greedy_mask_nms(stream,.8);assert [x['id'] for x in keep]==old['methods'][mode+'_pool']['ranking'];add('l60_initial_'+mode,aliases)
  for name,method in old['methods'].items():add('l60_'+name,method['aliases'])
  add('r72_point_prefilter',rec['point_prefilter_aliases'])
  for name,aliases in rec['contrast_prefilter_aliases'].items():add('r72_contrast_'+name,aliases)
  for name,method in rec['methods'].items():add('r72_'+name,method['aliases'])
  for j,c in enumerate(candidates):
   c['metadata']['preview']=f'{field}/mask-{j:04}.png'
   rgba=np.zeros((*c['mask'].shape,4),dtype=np.uint8);rgba[:,:,:3]=[0,210,130];rgba[:,:,3]=c['mask'].astype('uint8')*120;Image.fromarray(rgba).save(dest/f'mask-{j:04}.png',optimize=True)
  graph=build_graph(candidates,relations,5,{'field':old['field'],'origin_xy':old['origin_xy'],'protocol_sha256':sha(OUT/'protocol.json'),'planes':[{'z':p['z'],'path':'../r72/'+p['path'],'sha256':p['sha256']} for p in plane_info['planes']], 'source':'Public unlabeled marine fossil microscope field; R65, L60 and R72'})
  graph['rankings']={k:v['ranking'] for k,v in rec['methods'].items()}
  for edge in graph['relations']:
   a,b=byid[edge['candidate']]['mask'],byid[edge['kept']]['mask'];inter=int((a&b).sum());union=int((a|b).sum());edge['mask_iou']=inter/union if union else 0.;assert edge['mask_iou']>=.8-1e-12
  graphpath=OUT/(field+'.graph.json');graphpath.write_text(json.dumps(graph,separators=(',',':'))+'\n');np.savez_compressed(OUT/(field+'.masks.npz'),**pack_candidates(candidates))
  restored=unpack_candidates(np.load(OUT/(field+'.masks.npz'),allow_pickle=False));assert len(restored)==len(candidates)
  for c,node in zip(candidates,graph['candidates']):assert np.array_equal(restored[c['id']],c['mask']) and mask_digest(restored[c['id']])==node['mask_sha256']
  summaries.append({'field':old['field'],'candidates':len(candidates),'relations':len(relations),'graph':graphpath.name,'graph_sha256':sha(graphpath),'archive':field+'.masks.npz','archive_sha256':sha(OUT/(field+'.masks.npz'))});print(summaries[-1],flush=True)
 (OUT/'results.json').write_text(json.dumps({'format':'l63-results-v1','protocol_sha256':sha(OUT/'protocol.json'),'fields':summaries,'warning':'Unlabeled marine fossil fields; no measurement of segmentation accuracy or freshwater performance. Suppression links are not biological identity.'},indent=2)+'\n')
if __name__=='__main__':main()
