"""Choose additional image-space prompts without reference annotations."""
import hashlib,math
import cv2
import numpy as np


def order(point):
    return hashlib.sha256(f'l37-v1:{point[0]}:{point[1]}'.encode()).digest()


def select_extra(points, boxes, masks, *, size=512, extra_count=96, guided_cap=48):
    """Return deterministic 96-point uniform and model-guided selections.

    Guide uses expanded detector boxes and a 32-pixel band around the union of
    coarse predicted masks. At least half the points come from spatially
    unconditioned exploration. No reference annotations are accepted.
    """
    if type(size) is not int or size<=0 or type(extra_count) is not int or type(guided_cap) is not int or not 0<=guided_cap<=extra_count:
        raise ValueError('Invalid selection parameters')
    if not isinstance(points,list) or len(points)<extra_count or len(set(points))!=len(points):raise ValueError('Invalid point pool')
    for pt in points:
        if not isinstance(pt,tuple) or len(pt)!=2 or any(type(v) is not int or not 0<=v<size for v in pt):raise ValueError('Invalid coordinate')
    union=np.zeros((size,size),np.uint8)
    for m in masks:
        m=np.asarray(m)
        if m.shape!=(size,size):raise ValueError('Invalid candidate mask size')
        union|=m.astype(bool).astype('uint8')
    edge=cv2.morphologyEx(union,cv2.MORPH_GRADIENT,np.ones((3,3),np.uint8))
    zone=cv2.dilate(edge,cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(65,65)))
    for b in boxes:
        if len(b)!=4 or any(not isinstance(v,(int,float)) or isinstance(v,bool) or not math.isfinite(v) for v in b):raise ValueError('Invalid detector box')
        x0,y0,x1,y1=b
        if x0>=x1 or y0>=y1:raise ValueError('Invalid detector box')
        left=max(0,math.floor(x0-16));top=max(0,math.floor(y0-16));right=min(size,math.ceil(x1+16));bottom=min(size,math.ceil(y1+16))
        if left<right and top<bottom:zone[top:bottom,left:right]=1
    ordered=sorted(points,key=order);uniform=ordered[:extra_count];guided=[pt for pt in ordered if zone[pt[1],pt[0]]][:guided_cap]
    seen=set(guided);adaptive=guided+[pt for pt in ordered if pt not in seen][:extra_count-len(guided)]
    return {'uniform':uniform,'adaptive':adaptive,'guided_count':len(guided)}
