"""Conservative cross-stream mask deduplication with preserved alternatives."""
import numpy as np

def deduplicate(candidates,threshold=.95):
 """Keep the first ranked mask among near-identical cross-stream candidates.

 Candidate dicts require unique string `id`, `stream` in {'box','grid'} and
 equal-shaped 2D boolean masks. Return kept references and suppressed/kept ID
 pairs, leaving inputs and suppressed hypotheses intact for later recovery.
 No source labels or taxonomy are used.
 """
 if not isinstance(threshold,(float,int)) or isinstance(threshold,bool) or not 0<threshold<=1:raise ValueError('Invalid IoU threshold')
 kept=[];aliases=[];seen=set();shape=None;geometry={}
 for c in candidates:
  if not isinstance(c,dict) or not isinstance(c.get('id'),str) or c['id'] in seen or c.get('stream') not in ('box','grid'):raise ValueError('Invalid candidate identity or stream')
  mask=c.get('mask')
  if not isinstance(mask,np.ndarray) or mask.ndim!=2 or mask.dtype!=np.bool_:raise ValueError('Expected 2D boolean mask')
  if shape is None:shape=mask.shape
  if mask.shape!=shape:raise ValueError('Mask shape mismatch')
  seen.add(c['id']);area=int(np.count_nonzero(mask));ys,xs=np.nonzero(mask)
  geometry[c['id']]=(area,(int(xs.min()),int(ys.min()),int(xs.max())+1,int(ys.max())+1) if area else None);owner=None
  for k in kept:
   if k['stream']==c['stream']:continue
   old_area,old_box=geometry[k['id']];new_box=geometry[c['id']][1]
   if not area or not old_area or min(area,old_area)/max(area,old_area)<threshold:continue
   x0=max(new_box[0],old_box[0]);y0=max(new_box[1],old_box[1]);x1=min(new_box[2],old_box[2]);y1=min(new_box[3],old_box[3])
   if x0>=x1 or y0>=y1:continue
   intersection=np.count_nonzero(mask[y0:y1,x0:x1] & k['mask'][y0:y1,x0:x1]);union=area+old_area-intersection;iou=intersection/union
   if iou>=threshold:owner=k;break
  if owner is None:kept.append(c)
  else:aliases.append({'suppressed_id':c['id'],'kept_id':owner['id']})
 return {'kept':kept,'aliases':aliases}
