"""Add exploratory positive/negative prompt alternatives to a static bundle."""
import argparse
import json
from pathlib import Path

import cv2
import numpy as np
import torch
from PIL import Image
from torchvision.models import resnet18
from ultralytics import SAM

from run_field import embedding, sha256


def peaks(mask):
    distance = cv2.distanceTransform(mask.astype('uint8'), cv2.DIST_L2, 5)
    if distance.max() < 5:
        return None
    maxima = (distance == cv2.dilate(distance, np.ones((9,9),np.uint8))) & (distance >= max(5,.5*distance.max()))
    ys,xs = np.where(maxima)
    if not len(xs):
        return None
    order=np.argsort(-distance[ys,xs],kind='stable')
    first=order[0]; x1,y1=int(xs[first]),int(ys[first])
    second=next((idx for idx in order[1:] if (int(xs[idx])-x1)**2+(int(ys[idx])-y1)**2>=400),None)
    return None if second is None else [[x1,y1],[int(xs[second]),int(ys[second])]]


def main(argv=None):
    p=argparse.ArgumentParser(description=__doc__)
    p.add_argument('--bundle',type=Path,required=True)
    p.add_argument('--segmenter',type=Path,required=True)
    p.add_argument('--encoder',type=Path,required=True)
    p.add_argument('--gallery',type=Path,required=True)
    args=p.parse_args(argv)
    b=json.loads((args.bundle/'bundle.json').read_text())
    for path,key in ((args.segmenter,'segmenter_sha256'),(args.encoder,'encoder_sha256'),(args.gallery,'gallery_manifest_sha256')):
        if sha256(path)!=b['models'][key]:raise ValueError(f'{path} does not match original bundle')
    out=args.bundle/'split-alternatives.json'
    if out.exists():raise FileExistsError('Alternatives already exist for this bundle')
    raw=json.loads(args.gallery.read_text());rows=raw if isinstance(raw,list) else raw['rows']
    invalid={'none','nan','null','unknown','unidentified','n/a',''}
    rows=[r for r in rows if isinstance(r.get('species'),str) and r['species'].strip().casefold() not in invalid
          and r.get('local_file') and (not r.get('split') or r['split']=='gallery')]
    torch.set_num_threads(4)
    encoder=resnet18(weights=None);encoder.load_state_dict(torch.load(args.encoder,map_location='cpu',weights_only=True));encoder.fc=torch.nn.Identity();encoder.eval()
    references=[]
    for i,row in enumerate(rows,1):
        source=args.gallery.parent/row['local_file']; copied=args.bundle/f'references/{i:04d}.png'
        with Image.open(source) as original,Image.open(copied) as local:
            if original.convert('RGB').tobytes()!=local.convert('RGB').tobytes():raise ValueError(f'Reference image differs: {copied}')
            vector=embedding(encoder,local)
        references.append({'species':row['species'],'source_slide':row.get('source_slide'),
            'annotation_id':row.get('annotation_id'),'image':f'references/{i:04d}.png','source_sha256':sha256(source),'vector':vector})
    source=Image.open(args.bundle/b['field_image']).convert('RGB');image=cv2.cvtColor(np.asarray(source),cv2.COLOR_RGB2BGR)
    model=SAM(str(args.segmenter));dest=args.bundle/'split';dest.mkdir(exist_ok=False)
    hypotheses=[];parents=0
    for parent in b['candidates']:
        if not parent['mask']:continue
        mask=np.asarray(Image.open(args.bundle/parent['mask']).convert('L'))>0
        points=peaks(mask)
        if points is None:continue
        parents+=1;retained=[mask]
        for j in range(2):
            point_order=[points[j],points[1-j]]
            result=model.predict(image,points=[point_order],labels=[[1,0]],imgsz=768,device='cpu',retina_masks=True,verbose=False)[0]
            if result.masks is None or len(result.masks.data)!=1:continue
            new=result.masks.data[0].cpu().numpy().astype(bool)
            if new.shape!=mask.shape:raise ValueError('Mask size mismatch')
            area=int(new.sum());quality=float(result.boxes.conf[0].cpu())
            if not 300<=area<=50000 or quality<.6:continue
            if any((new&other).sum()/(new|other).sum()>=.8 for other in retained):continue
            retained.append(new);ys,xs=np.where(new);box=[int(xs.min()),int(ys.min()),int(xs.max()+1),int(ys.max()+1)]
            ident=f"split-{parent['id']}-{j+1}";mask_file=f'split/{ident}-mask.png';crop_file=f'split/{ident}-crop.png'
            Image.fromarray(new.astype('uint8')*255).save(args.bundle/mask_file)
            crop=source.crop(tuple(box));crop.save(args.bundle/crop_file);vector=embedding(encoder,crop)
            ranked=sorted(((float(np.dot(vector,r['vector'])),r) for r in references),key=lambda item:-item[0])
            suggestions=[];seen=set()
            for score,ref in ranked:
                if ref['species'] in seen:continue
                seen.add(ref['species']);suggestions.append({k:v for k,v in ref.items() if k!='vector'}|{'similarity':score})
                if len(suggestions)==3:break
            hypotheses.append({'id':ident,'parent_candidate_id':parent['id'],'source':'split_hypothesis',
                'box':box,'mask':mask_file,'crop':crop_file,'model_mask_score':quality,
                'positive_point':point_order[0],'negative_point':point_order[1],
                'suggestions':suggestions,'classification':'unresolved'})
    output={'format':'diatom-split-alternatives-v1','bundle_id':b['bundle_id'],
            'method':'distance peaks with swapped positive/negative prompts', 'parents_with_two_peaks':parents,
            'area_range':[300,50000],'minimum_mask_score':.6,'duplicate_iou':.8,'hypotheses':hypotheses}
    out.write_text(json.dumps(output,indent=2)+'\n')
    print(f'{parents} candidates with two peaks; {len(hypotheses)} retained split hypotheses',flush=True)


if __name__=='__main__':main()
