"""Build reversible candidate alternatives from image-only stack shifts."""
from .phase_alignment import shift_mask

def build_variants(candidates, peaks_by_plane, limit=3, reference_plane=2):
    """Return fixed orderings; image shifts are reference-to-target XY.

    Masks outside the field may become empty; they remain in the returned
    alternatives for provenance and should be excluded from review rankings.
    """
    if limit < 1:
        raise ValueError('limit must be positive')
    groups=[]
    for candidate in candidates:
        z=int(candidate['z']); options=[]
        peaks=[] if z==reference_plane else peaks_by_plane.get(z, [])[:limit]
        for peak in peaks:
            shift=(int(peak['dx']),int(peak['dy']))
            if shift not in options: options.append(shift)
        if not options: options.append((0,0))
        if (0,0) not in options: options.append((0,0))
        group=[]
        for j,(dx,dy) in enumerate(options):
            mask=shift_mask(candidate['mask'],-dx,-dy)
            group.append({'id':str(candidate['id'])+'|h'+str(j),'source_id':str(candidate['id']),
                          'z':z,'dx':dx,'dy':dy,'branch':j,'mask':mask})
        groups.append(group)
    single=[g[0] for g in groups]
    primary=[g[j] for j in range(max((len(g) for g in groups),default=0)) for g in groups if j<len(g)]
    interleaved=[v for g in groups for v in g]
    identity=[{'id':str(c['id'])+'|raw','source_id':str(c['id']),'z':int(c['z']),
               'dx':0,'dy':0,'branch':-1,'mask':c['mask']} for c in candidates]
    return {'unregistered':identity,'phase_single':single,'multi_primary':primary,'multi_interleaved':interleaved}
