"""Try automatic negative-point splitting of existing grid masks, without target labels."""
import json
import sys
import time
from pathlib import Path

import cv2
import numpy as np
import torch
from PIL import Image,ImageDraw,ImageFont
from ultralytics.models.sam import Predictor

ROOT=Path(__file__).resolve().parent.parent
sys.path.insert(0,str(ROOT/'research'))
from r18_pair_data import load_pair

selection=json.loads((ROOT/'results/r18/selection.json').read_text())['selected_pairs']
previous=json.loads((ROOT/'results/l19/grid-proposals.json').read_text())['records']
OUT=ROOT/'results/l20';OUT.mkdir(exist_ok=True)
torch.set_num_threads(4)
font=ImageFont.truetype('DejaVuSans.ttf',15);plate=Image.new('RGB',(1320,len(selection)*410),'#f8f8f2');draw=ImageDraw.Draw(plate)
records=[]
for i,row in enumerate(selection,1):
    image,refs,path=load_pair(i,row);H,W=image.shape[:2]
    old=[]
    for x in previous[i-1]['candidates']:
        mask=np.asarray(Image.open(ROOT/'results/l19'/x['mask_file']).convert('L'))>0
        if mask.shape!=(H,W):raise ValueError('Candidate mask dimension mismatch')
        old.append({'mask':mask,'score':x['score'],'origin':'grid'})
    prompts=[];parents=[]
    for n,c in enumerate(old):
        m=c['mask'].astype('uint8');dist=cv2.distanceTransform(m,cv2.DIST_L2,5)
        if dist.max()<5:continue
        # Two high interior-distance local maxima at least 20 pixels apart.
        peak=(dist==cv2.dilate(dist,np.ones((9,9),np.uint8)))&(dist>=max(5,.5*dist.max()))
        ys,xs=np.where(peak)
        if len(xs)<2:continue
        order=np.argsort(-dist[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>=20**2),None)
        if second is None:continue
        x2,y2=int(xs[second]),int(ys[second]);parents.append({'candidate_index':n,'points':[[x1,y1],[x2,y2]]})
        prompts.extend([[[x1,y1],[x2,y2]],[[x2,y2],[x1,y1]]])
    model=Predictor(overrides={'model':'/tmp/mobile_sam.pt','task':'segment','mode':'predict','imgsz':768,
          'device':'cpu','retina_masks':True,'verbose':False,'save':False,'conf':0.0})
    start=time.monotonic();model.set_image(cv2.cvtColor(image,cv2.COLOR_RGB2BGR));new=[]
    for n in range(0,len(prompts),12):
        batch=prompts[n:n+12]
        pred=model(points=batch,labels=[[1,0] for _ in batch],verbose=False)[0]
        if pred.masks is None:continue
        for mask,score in zip(pred.masks.data.cpu().numpy(),pred.boxes.conf.cpu().numpy()):
            mask=mask.astype(bool);area=int(mask.sum())
            if mask.shape!=(H,W):raise ValueError('Unexpected mask dimensions')
            if 300<=area<=50000 and float(score)>=.6:new.append({'mask':mask,'score':float(score),'origin':'automatic split'})
    # Keep all original candidates. Suppress each new mask against originals and earlier new masks.
    retained=old.copy()
    for c in sorted(new,key=lambda c:-c['score']):
        area=c['mask'].sum()
        if all((lambda inter,union: not union or inter/union<.8)(np.logical_and(c['mask'],o['mask']).sum(),
               np.logical_or(c['mask'],o['mask']).sum()) for o in retained):retained.append(c)
    scores=[]
    for ref in refs:
        scores.append([float(np.logical_and(ref,c['mask']).sum()/np.logical_or(ref,c['mask']).sum()) for c in retained])
    best=None
    for a in [None]+list(range(len(retained))):
        for b in [None]+list(range(len(retained))):
            if a is not None and b is not None and a==b:continue
            if a is not None and scores[0][a]<.5:continue
            if b is not None and scores[1][b]<.5:continue
            rank=((a is not None)+(b is not None),(scores[0][a] if a is not None else 0)+(scores[1][b] if b is not None else 0))
            if best is None or rank>best[0]:best=(rank,(a,b))
    match=best[1]
    case=OUT/f'case-{i:02d}';case.mkdir(exist_ok=True)
    for j,c in enumerate(retained):Image.fromarray(c['mask'].astype('uint8')*255).save(case/f'mask-{j:03d}.png')
    record={'image_file':row['image']['file_name'],'original_count':len(old),'parents_with_two_peaks':len(parents),
            'new_before_nms':len(new),'total_candidates':len(retained),'matched_indices':list(match),
            'parent_hypotheses':parents,
            'candidates':[{'mask_file':f'case-{i:02d}/mask-{j:03d}.png','score':c['score'],'origin':c['origin']} for j,c in enumerate(retained)],
            'matched_ious':[scores[j][v] if v is not None else None for j,v in enumerate(match)],
            'matched_origins':[retained[v]['origin'] if v is not None else None for v in match],
            'elapsed_seconds':time.monotonic()-start}
    records.append(record)
    union=np.logical_or(*refs);ys,xs=np.where(union);left=max(0,int(xs.min())-55);right=min(W,int(xs.max())+56);top=max(0,int(ys.min())-55);bottom=min(H,int(ys.max())+56)
    for col,title in enumerate(('Annotated pair','All candidate outlines','Matched masks (reference-selected)')):
        im=Image.fromarray(image).convert('RGBA')
        if col==2:
            for j,idx in enumerate(match):
                if idx is None:continue
                color=[(0,185,150,100),(238,80,155,100)][j];layer=Image.new('RGBA',im.size,color)
                layer.putalpha(Image.fromarray(retained[idx]['mask'].astype('uint8')*color[3]));im=Image.alpha_composite(im,layer)
        d=ImageDraw.Draw(im)
        if col==0:
            for ref,color in zip(refs,['#00d6ad','#ed4ab5']):
                contours,_=cv2.findContours(ref,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
                for contour in contours:
                    line=[tuple(int(v) for v in p) for p in contour[:,0,:]]
                    if len(line)>1:d.line(line+[line[0]],fill=color,width=2)
        if col==1:
            for candidate in retained:
                contours,_=cv2.findContours(candidate['mask'].astype('uint8'),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
                for contour in contours:
                    line=[tuple(int(v) for v in p) for p in contour[:,0,:]]
                    if len(line)>1:d.line(line+[line[0]],fill='#00d6ad',width=1)
        crop=im.convert('RGB').crop((left,top,right,bottom));crop.thumbnail((390,330),Image.Resampling.LANCZOS)
        x=col*440+8;y=(i-1)*410+50;plate.paste(crop,(x,y));draw.text((x,(i-1)*410+5),f'{i}. {title}',font=font,fill='#193b36')
        if col==1:draw.text((x,(i-1)*410+25),f'{len(old)} → {len(retained)} full-field masks',font=font,fill='#193b36')
        if col==2:draw.text((x,(i-1)*410+25),'IoUs '+', '.join('miss' if v is None else f'{v:.2f}' for v in record['matched_ious']),font=font,fill='#193b36')
    print(i,row['image']['file_name'],'parents',len(parents),'candidates',len(old),'->',len(retained),'matches',record['matched_ious'],record['matched_origins'],flush=True)
plate.save(OUT/'split-grid.jpg',quality=90)
(OUT/'split-grid.json').write_text(json.dumps({'rule':'two interior-distance peaks 20 pixels apart, negative cross-prompt, no labels used to generate candidates',
 'score_threshold':.6,'mask_iou_nms':.8,'match_iou':.5,'records':records},indent=2))
