"""Conditional MobileSAM comparison against six public COCO polygon annotations."""
import hashlib
import json
import time
from pathlib import Path

import cv2
import numpy as np
import torch
from PIL import Image,ImageDraw,ImageFont
from ultralytics import SAM

ROOT=Path(__file__).resolve().parent.parent
OUT=ROOT/'results/r16'
selection=json.loads((OUT/'selection.json').read_text())['selection']
torch.set_num_threads(4)
model=SAM('/tmp/mobile_sam.pt')
font=ImageFont.truetype('DejaVuSans.ttf',15)
plate=Image.new('RGB',(1300,len(selection)*360),'#f8f8f2');draw=ImageDraw.Draw(plate)
records=[]
for i,entry in enumerate(selection,1):
    annotation=json.loads((Path('/tmp/diatom-mask-coco')/entry['annotation_file']).read_text())
    annotations=[a for a in annotation['annotations'] if a['image_id']==entry['image']['id']]
    if len(annotations)!=1:raise ValueError('This fixed selection expects one annotation per image')
    ann=annotations[0];path=Path('/tmp/diatom-mask-images')/f'{i:02d}.jpg'
    image=np.asarray(Image.open(path).convert('RGB'))
    h,w=image.shape[:2]
    if (w,h)!=(entry['image']['width'],entry['image']['height']):raise ValueError('Image dimensions disagree')
    scale=768/max(w,h);W,H=round(w*scale),round(h*scale)
    image=cv2.resize(image,(W,H),interpolation=cv2.INTER_AREA)
    reference=np.zeros((H,W),dtype=np.uint8)
    for polygon in ann['segmentation']:
        xy=np.asarray(polygon,dtype=np.float32).reshape(-1,2);xy[:,0]*=W/w;xy[:,1]*=H/h
        cv2.fillPoly(reference,[np.rint(xy).astype(np.int32)],1)
    if not reference.any():raise ValueError('Empty annotation polygon')
    distance=cv2.distanceTransform(reference,cv2.DIST_L2,5);py,px=np.unravel_index(distance.argmax(),distance.shape)
    ys,xs=np.where(reference);box=[int(xs.min()),int(ys.min()),int(xs.max()+1),int(ys.max()+1)]
    masks=[];variants=[]
    for kind in ('point','box'):
        kwargs={'points':[int(px),int(py)],'labels':[1]} if kind=='point' else {'bboxes':box}
        start=time.monotonic()
        # Ultralytics treats NumPy color inputs as BGR; the displayed PIL image is RGB.
        prediction=model.predict(cv2.cvtColor(image,cv2.COLOR_RGB2BGR),imgsz=768,device='cpu',retina_masks=True,verbose=False,**kwargs)[0]
        if prediction.masks is None or len(prediction.masks.data)!=1:raise ValueError('Expected exactly one mask')
        mask=prediction.masks.data[0].cpu().numpy().astype(bool)
        if mask.shape!=reference.shape:raise ValueError(f'Unexpected mask dimensions {mask.shape}')
        intersection=np.logical_and(mask,reference).sum();union=np.logical_or(mask,reference).sum()
        variants.append({'prompt':kind,'iou':float(intersection/union),'predicted_area_pixels':int(mask.sum()),
                         'elapsed_seconds':time.monotonic()-start})
        masks.append(mask)
    r={'image_file':entry['image']['file_name'],'category':entry['category'],'source_sha256':hashlib.sha256(path.read_bytes()).hexdigest(),
       'image_size_original':[w,h],'image_size_model':[W,H],'annotation_id':ann['id'],'point_xy':[int(px),int(py)],
       'box_xyxy':box,'reference_area_pixels':int(reference.sum()),'variants':variants}
    records.append(r)
    # Display crop keeps context around the reference; the evaluation uses the full resized image.
    margin=75;left=max(0,box[0]-margin);top=max(0,box[1]-margin);right=min(W,box[2]+margin);bottom=min(H,box[3]+margin)
    contours,_=cv2.findContours(reference,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
    contour_lines=[[(int(x),int(y)) for x,y in c[:,0,:]] for c in contours]
    for col,(label,mask) in enumerate((('Public polygon',None),('Point prompt',masks[0]),('Box prompt',masks[1]))):
        view=Image.fromarray(image).convert('RGBA')
        if mask is not None:
            layer=Image.new('RGBA',view.size,(0,185,150,0));layer.putalpha(Image.fromarray(mask.astype('uint8')*105));view=Image.alpha_composite(view,layer)
        d=ImageDraw.Draw(view)
        for line in contour_lines:
            if len(line)>1:d.line(line+[line[0]],fill='#ffce36',width=2)
        if col==1:d.ellipse((int(px)-5,int(py)-5,int(px)+5,int(py)+5),outline='#ed4ab5',width=3)
        if col==2:d.rectangle(box,outline='#ed4ab5',width=2)
        crop=view.convert('RGB').crop((left,top,right,bottom));crop.thumbnail((390,300),Image.Resampling.LANCZOS)
        x=col*430+8;y=(i-1)*360+50;plate.paste(crop,(x,y))
        suffix='' if col==0 else f" · IoU {variants[col-1]['iou']:.2f}"
        draw.text((x,(i-1)*360+5),f"{i}. {entry['category'].split('_')[0]} · {label}{suffix}",font=font,fill='#193b36')
    print(i,entry['image']['file_name'],[(v['prompt'],round(v['iou'],3)) for v in variants],flush=True)
plate.save(OUT/'prompted-masks.jpg',quality=90)
(OUT/'prompted-masks.json').write_text(json.dumps({'source':'https://doi.org/10.5281/zenodo.21295927',
 'sampling':'Three test-named images per genus; excludes filename overlaps across named splits; one source polygon per selected image',
 'model':'MobileSAM','checkpoint_sha256':hashlib.sha256(Path('/tmp/mobile_sam.pt').read_bytes()).hexdigest(),
 'records':records},indent=2))
