"""Label-free, reversible ranking of candidate masks; original masks preserved."""
import numpy as np

def _prepare(candidates):
 if not isinstance(candidates,list):raise ValueError('Expected a candidate list')
 seen=set();shape=None;meta=[]
 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')
  m=c.get('mask')
  if not isinstance(m,np.ndarray) or m.ndim!=2 or m.dtype!=np.bool_:raise ValueError('Expected a 2D boolean mask')
  if shape is None:shape=m.shape
  if m.shape!=shape:raise ValueError('Inconsistent mask shape')
  seen.add(c['id']);ys,xs=np.nonzero(m);area=int(len(xs));box=(int(xs.min()),int(ys.min()),int(xs.max())+1,int(ys.max())+1) if area else None;meta.append((area,box))
 return meta

def _iou(a,b,ma,mb):
 aa,ba=ma;ab,bb=mb
 if not aa or not ab:return 0.
 x0=max(ba[0],bb[0]);y0=max(ba[1],bb[1]);x1=min(ba[2],bb[2]);y1=min(ba[3],bb[3])
 if x0>=x1 or y0>=y1:return 0.
 inter=int(np.count_nonzero(a[y0:y1,x0:x1]&b[y0:y1,x0:x1]));return inter/(aa+ab-inter)

def consensus_interleave(candidates,threshold=.5):
 """Alternate cross-stream-supported hypotheses with the existing rank.

 Support uses masks only; all candidates, including unsupported, remain.
 """
 if not 0<threshold<=1:raise ValueError('Invalid threshold')
 meta=_prepare(candidates);supported=[]
 for i,c in enumerate(candidates):
  if any(c['stream']!=d['stream'] and _iou(c['mask'],d['mask'],meta[i],meta[j])>=threshold for j,d in enumerate(candidates) if i!=j):supported.append(c)
 result=[];seen=set()
 for i in range(max(len(candidates),len(supported))):
  for rank in (supported,candidates):
   if i<len(rank) and rank[i]['id'] not in seen:result.append(rank[i]);seen.add(rank[i]['id'])
 return result

def diversity_rank(candidates,pool=80,penalty=.8):
 """Diversify first `pool` original candidates; append remaining unchanged.

 Greedy score is inverse original rank times 1 minus penalty times maximum
 IoU with earlier selected masks. This is ranking, not suppression.
 """
 if type(pool) is not int or pool<1 or not 0<=penalty<=1:raise ValueError('Invalid ranking parameters')
 meta=_prepare(candidates);n=min(pool,len(candidates));remaining=list(range(n));chosen=[];max_seen=[0.]*n
 while remaining:
  idx=max(remaining,key=lambda i:((1-penalty*max_seen[i])/(i+1),-i));remaining.remove(idx);chosen.append(idx)
  for j in remaining:max_seen[j]=max(max_seen[j],_iou(candidates[idx]['mask'],candidates[j]['mask'],meta[idx],meta[j]))
 return [candidates[i] for i in chosen]+candidates[n:]
