"""Defer geometrically similar cross-model hypotheses without deleting them."""
import numpy as np

def _iou(a,b):
 inter=int(np.count_nonzero(a&b));union=int(np.count_nonzero(a|b));return inter/union if union else 0.

def defer_cross_model(items,threshold):
 """Stable two-tier order plus direct deferral links, never identity labels.

 Candidate is deferred if it has IoU >= threshold with the first earlier
 nondeferred candidate from a different source. Within-tier order follows
 input order. Deferred candidates stay in the output; all input masks survive.
 """
 if not np.isfinite(threshold) or not 0<threshold<=1:raise ValueError('Invalid threshold')
 ids=set();shape=None;primary=[];deferred=[];links=[]
 for c in items:
  if not isinstance(c,dict) or not isinstance(c.get('id'),str) or not c['id'] or c['id'] in ids or not isinstance(c.get('source'),str) or not c['source']:raise ValueError('Invalid candidate')
  m=c.get('mask')
  if not isinstance(m,np.ndarray) or m.ndim!=2 or m.dtype!=np.bool_ or (shape is not None and m.shape!=shape):raise ValueError('Invalid mask')
  shape=m.shape;ids.add(c['id']);anchor=None;value=0.
  for prior in primary:
   if c['source']!=prior['source']:
    score=_iou(m,prior['mask'])
    if score>=threshold:anchor=prior;value=score;break
  if anchor is None:primary.append(c)
  else:
   deferred.append(c);links.append({'candidate':c['id'],'anchor':anchor['id'],'iou':value,'semantics':'ranking_deferral_not_identity'})
 return primary+deferred,links
