"""Reference-free rankings of proposal masks; no masks are discarded."""
import numpy as np

_BITCOUNT=np.array([i.bit_count() for i in range(256)],dtype=np.uint8)

def _validate(items):
 ids=[x['id'] for x in items]
 if len(set(ids))!=len(ids):raise ValueError('Duplicate IDs')
 if not items:return
 shape=items[0]['mask'].shape
 if len(shape)!=2 or any(not isinstance(x['mask'],np.ndarray) or x['mask'].dtype!=np.bool_ or x['mask'].shape!=shape or not np.isfinite(x['quality']) for x in items):raise ValueError('Invalid proposals')

def quality_order(items):
 _validate(items)
 return sorted(items,key=lambda x:-x['quality'])

def spatial_round_robin(items,cells=4):
 """Interleave baseline-ranked proposals by their centroids' grid cells."""
 _validate(items)
 if cells<1:raise ValueError('Invalid grid')
 groups={}
 for item in items:
  ys,xs=np.nonzero(item['mask'])
  if not len(xs):cell=(-1,-1)
  else:cell=(min(cells-1,int(xs.mean()*cells/item['mask'].shape[1])),min(cells-1,int(ys.mean()*cells/item['mask'].shape[0])))
  groups.setdefault(cell,[]).append(item)
 return [group[j] for j in range(max(map(len,groups.values()),default=0)) for group in groups.values() if j<len(group)]

def stability_interleave(items,aliases,points):
 """Interleave baseline with prompt-repeatability, without deleting aliases.

 Repeatability = (1 + direct suppression count) / (1 + all grid prompt
 points inside the retained mask). It is a heuristic, not probability.
 """
 _validate(items);points=np.asarray(points)
 if points.ndim!=2 or points.shape[1]!=2:raise ValueError('Expected Nx2 points')
 counts={x['id']:0 for x in items}
 for e in aliases:
  if e['kept'] not in counts:raise ValueError('Unknown kept proposal')
  counts[e['kept']]+=1
 def score(c):
  m=c['mask'];x=points[:,0].astype(int);y=points[:,1].astype(int)
  if np.any(x<0) or np.any(x>=m.shape[1]) or np.any(y<0) or np.any(y>=m.shape[0]):raise ValueError('Point outside image')
  return (1+counts[c['id']])/(1+int(m[y,x].sum()))
 alt=sorted(items,key=lambda x:(-score(x),-x['quality']))
 out=[];seen=set()
 for j in range(len(items)):
  for x in (items[j],alt[j]):
   if x['id'] not in seen:out.append(x);seen.add(x['id'])
 return out

def diverse_order(items):
 """Greedy equal weighting of baseline rank and mask dissimilarity."""
 _validate(items);n=len(items)
 if not n:return []
 packs=[np.packbits(x['mask'].ravel()) for x in items];areas=[int(x['mask'].sum()) for x in items];remaining=list(range(n));max_iou=np.zeros(n);out=[]
 while remaining:
  best=max(remaining,key=lambda j:(.5*(1-j/max(1,n-1))+.5*(1-max_iou[j]),-j));remaining.remove(best);out.append(items[best])
  for j in remaining:
   inter=int(_BITCOUNT[np.bitwise_and(packs[best],packs[j])].sum());union=areas[best]+areas[j]-inter;max_iou[j]=max(max_iou[j],inter/union if union else 0.)
 return out
