"""Compare point-prompt masks at the annotated focus and local contrast peak."""
import csv
import json
import sys
from pathlib import Path

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

ROOT=Path(__file__).resolve().parent.parent
sys.path.insert(0,str(ROOT/'experiments'))
from scan_fields import Stack

torch.set_num_threads(4)
model=SAM('/tmp/mobile_sam.pt')
fields=json.loads((ROOT/'results/diatom-practice-round1.json').read_text())['fields']
cross=json.loads((ROOT/'results/r6/marked-crossings.json').read_text())
with (ROOT/'results/l2/focus-scores.csv').open(newline='') as f:
    focus=list(csv.DictReader(f))
out=ROOT/'results/l2'
font=ImageFont.truetype('DejaVuSans.ttf',15)
plate=Image.new('RGB',(1000,len(cross)*320),'#f8f8f2');draw=ImageDraw.Draw(plate)
records=[]
for i,r in enumerate(cross):
    field=next(f for f in fields if f['slide']==r['slide'] and f['field']==r['field'])
    row=next(x for x in focus if x['slide']==r['slide'] and int(x['field'])==r['field'] and int(x['mark_number'])==r['mark_number'])
    selected=int(row['local_best_z']);marked=r['z'];x,y=r['point']
    old=np.asarray(Image.open(ROOT/'results/r6'/r['mask_file']).convert('L'))>0
    with Stack(ROOT/'scans'/r['slide']) as stack:
        images=[stack.field(z,*field['origin_xy'],768) for z in (marked,selected)]
    if selected==marked:
        new=old.copy()
    else:
        prediction=model.predict(np.asarray(images[1].convert('RGB')),points=[x,y],labels=[1],
                                 imgsz=768,device='cpu',verbose=False)[0]
        if prediction.masks is None or len(prediction.masks.data)!=1:
            raise ValueError('Expected a single mask')
        new=prediction.masks.data[0].cpu().numpy().astype(bool)
    intersection=np.logical_and(old,new).sum();union=np.logical_or(old,new).sum()
    mask_name=f'local-focus-mask-{i+1:02d}.png'
    Image.fromarray(new.astype('uint8')*255).save(out/mask_name)
    record={'slide':r['slide'],'field':r['field'],'mark_number':r['mark_number'],'point':[x,y],
            'marked_z':marked,'local_peak_z':selected,'marked_area':int(old.sum()),'peak_area':int(new.sum()),
            'marked_mask_file':f"/results/r6/{r['mask_file']}",'local_focus_mask_file':mask_name,
            'mask_iou':float(intersection/union) if union else None,
            'marked_point_retained':bool(old[y,x]),'peak_point_retained':bool(new[y,x])}
    records.append(record)
    for j,(im,mask,z) in enumerate(zip(images,(old,new),(marked,selected))):
        base=ImageOps.autocontrast(im,cutoff=.25).convert('RGBA')
        layer=Image.new('RGBA',base.size,(0,175,145,0));layer.putalpha(Image.fromarray(mask.astype('uint8')*105))
        view=Image.alpha_composite(base,layer).convert('RGB')
        d=ImageDraw.Draw(view);d.ellipse((x-5,y-5,x+5,y+5),outline='#ffcf36',width=3)
        left=max(0,min(768-300,x-150));top=max(0,min(768-270,y-135))
        px=j*440+8;py=i*320+45
        plate.paste(view.crop((left,top,left+300,top+270)),(px,py))
        title='Recorded plane' if j==0 else 'Local contrast peak'
        draw.text((px,i*320+5),f"{r['slide'][:9]} mark {r['mark_number']} · {title} z={z}",font=font,fill='#193b36')
        if j:draw.text((px,i*320+25),f"mask IoU with left: {record['mask_iou']:.2f}",font=font,fill='#193b36')
    print(i+1,'marked',marked,'peak',selected,'IoU',round(record['mask_iou'],3),flush=True)
plate.save(out/'focused-masks.jpg',quality=90)
(out/'focused-masks.json').write_text(json.dumps(records,indent=2))
different=[r for r in records if r['marked_z']!=r['local_peak_z']]
print('different planes',len(different),'median mask IoU',float(np.median([r['mask_iou'] for r in different])) if different else 'n/a')
