"""Compare detector-box and detector-center prompts on one marked field."""
import csv
import hashlib
import json
import sys
from pathlib import Path

import cv2
import numpy as np
import torch
from PIL import Image,ImageDraw,ImageFont
from torchvision.transforms import Compose,CenterCrop,Resize,ToTensor,Normalize,InterpolationMode
from ultralytics import SAM,YOLO
from ultralytics.nn.tasks import ClassificationModel
from ultralytics.nn.modules import Conv,C2f,Bottleneck,Classify
from torch.nn import Sequential,Conv2d,BatchNorm2d,SiLU,ModuleList,AdaptiveAvgPool2d,Linear,Dropout

from diamorph_mask_orientation import mask_crop
from diamorph_preview import WEIGHTS,TAXA,preprocess
sys.path.insert(0,str(Path(__file__).resolve().parent.parent/'research'))
from r1_anchor_matching import maximum_matching

ROOT=Path(__file__).resolve().parent.parent
BUNDLE=ROOT/'results/pilot/field-01'
OUT=ROOT/'results/pilot/full-field-center'


def match_masks(points,masks):
    """Maximum one-to-one point containment; no claim that marks are truth."""
    edges=[]
    for x,y in points:
        options=[]
        for i,mask in enumerate(masks):
            if mask is not None and 0<=int(y)<mask.shape[0] and 0<=int(x)<mask.shape[1] and mask[int(y),int(x)]:options.append(i)
        edges.append(options)
    owners={}
    def visit(point,seen):
        for i in edges[point]:
            if i in seen:continue
            seen.add(i)
            if i not in owners or visit(owners[i],seen):owners[i]=point;return True
        return False
    for p in sorted(range(len(points)),key=lambda x:len(edges[x])):visit(p,set())
    return sorted((point,mask) for mask,point in owners.items())


def main():
    b=json.loads((BUNDLE/'bundle.json').read_text());baseline=json.loads((ROOT/'results/pilot/diamorph-diagnostic/preview.json').read_text())
    if b['bundle_id']!=baseline['bundle_id'] or hashlib.sha256(WEIGHTS.read_bytes()).hexdigest()!=baseline['model_sha256']:
        raise ValueError('Bundle or classifier mismatch')
    reference=json.loads((ROOT/'results/diatom-practice-round1.json').read_text())['fields']
    fields=[f for f in reference if f['slide']==b['slide'] and f['origin_xy']==b['origin_xy']]
    if len(fields)!=1:raise ValueError('Expected exactly one corresponding practice field')
    points=[(m['x'],m['y']) for m in fields[0]['marks'] if m['kind']=='Possible diatom']
    image=cv2.imread(str(BUNDLE/b['field_image']));size=b['size']
    if image is None or image.shape[:2]!=(size,size):raise ValueError('Invalid bundle image')
    torch.set_num_threads(4)
    allow=[ClassificationModel,Conv,C2f,Bottleneck,Classify,Sequential,Conv2d,BatchNorm2d,SiLU,
           ModuleList,AdaptiveAvgPool2d,Linear,Dropout,Compose,CenterCrop,Resize,ToTensor,Normalize,InterpolationMode]
    with torch.serialization.safe_globals(allow):checkpoint=torch.load(WEIGHTS,map_location='cpu',weights_only=True)
    trained=checkpoint['model'].float();classifier=YOLO('yolov8l-cls.yaml',task='classify');classifier.model=trained
    model_path=Path('/tmp/mobile_sam.pt')
    if hashlib.sha256(model_path.read_bytes()).hexdigest()!=b['models']['segmenter_sha256']:raise ValueError('Segmenter mismatch')
    sam=SAM(str(model_path));taxa={x['taxonomic_code']:x for x in csv.DictReader(TAXA.open(),delimiter=';')}
    original_masks=[];center_masks=[];records=[];examples=[];OUT.mkdir(parents=True,exist_ok=True)
    for candidate in b['candidates']:
        x0,y0,x1,y1=candidate['box'];point=[round((x0+x1)/2),round((y0+y1)/2)]
        orig=np.asarray(Image.open(BUNDLE/candidate['mask']).convert('L'))>0 if candidate['mask'] else None
        result=sam.predict(image,points=[[point]],labels=[[1]],imgsz=768,device='cpu',retina_masks=True,verbose=False)[0]
        center=None if result.masks is None or len(result.masks.data)!=1 else result.masks.data[0].cpu().numpy().astype(bool)
        if center is not None and center.shape!=(size,size):raise ValueError('Unexpected mask dimensions')
        original_masks.append(orig);center_masks.append(center)
        old=next(x for x in baseline['records'] if x['candidate_id']==candidate['id'])['top_five'][0]
        row={'candidate_id':candidate['id'],'detector_box':candidate['box'],'positive_point':point,
             'baseline_classifier':old,'box_mask_pixels':int(orig.sum()) if orig is not None else None,
             'center_mask_pixels':int(center.sum()) if center is not None else None}
        if orig is not None and center is not None:
            union=int((orig|center).sum());row['box_center_mask_iou']=float((orig&center).sum()/union) if union else None
        oriented=None
        if orig is not None:
            try:
                box_oriented=mask_crop(image,orig)
                pixel_scale=(b['calibration']['x_um_per_pixel']+b['calibration']['y_um_per_pixel'])/2
                box_prepared=preprocess(box_oriented,pixel_scale,pixel_scale)
                box_pred=classifier.predict(box_prepared,imgsz=512,device='cpu',verbose=False)[0]
                box_code=trained.names[int(box_pred.probs.top1)]
                row['box_oriented_classifier']={'code':box_code,'species':taxa[box_code]['species'],
                    'genus':taxa[box_code]['genus'],'score':float(box_pred.probs.top1conf.cpu())}
            except ValueError as exc:row['box_orientation_error']=str(exc)
        if center is not None:
            name=f"{candidate['id']}-center-mask.png";Image.fromarray(center.astype('uint8')*255).save(OUT/name);row['center_mask_file']=name
            try:
                oriented=mask_crop(image,center)
                # Rotation mixes X and Y axes; the native scales differ by less than 0.03%.
                pixel_scale=(b['calibration']['x_um_per_pixel']+b['calibration']['y_um_per_pixel'])/2
                prepared=preprocess(oriented,pixel_scale,pixel_scale)
                pred=classifier.predict(prepared,imgsz=512,device='cpu',verbose=False)[0]
                code=trained.names[int(pred.probs.top1)];row['center_oriented_classifier']={'code':code,'species':taxa[code]['species'],
                    'genus':taxa[code]['genus'],'score':float(pred.probs.top1conf.cpu())}
            except ValueError as exc:row['orientation_error']=str(exc)
        records.append(row);examples.append((row,orig,center,oriented))
        print(candidate['id'],'box/center IoU',round(row.get('box_center_mask_iou') or 0,3),
              'taxon',old['code'],'->',row.get('center_oriented_classifier',{}).get('code','no result'),flush=True)
    boxes=[x['box'] for x in b['candidates']]
    summary={'provisional_possible_marks':len(points),'candidates':len(boxes),
             'boxes_point_assignments':len(maximum_matching(points,boxes)[0]),
             'box_masks_point_assignments':len(match_masks(points,original_masks)),
             'center_masks_point_assignments':len(match_masks(points,center_masks)),
             'classifier_top_code_changes_vs_baseline':sum('center_oriented_classifier' in r and r['center_oriented_classifier']['code']!=r['baseline_classifier']['code'] for r in records),
             'center_vs_box_oriented_top_code_changes':sum('center_oriented_classifier' in r and 'box_oriented_classifier' in r and r['center_oriented_classifier']['code']!=r['box_oriented_classifier']['code'] for r in records)}
    (OUT/'comparison.json').write_text(json.dumps({'bundle_id':b['bundle_id'],'classifier_sha256':baseline['model_sha256'],
        'segmenter_sha256':b['models']['segmenter_sha256'],'summary':summary,'records':records},indent=2)+'\n')
    font=ImageFont.truetype('DejaVuSans.ttf',14);plate=Image.new('RGB',(1210,len(examples)*235),'#f8f8f2');draw=ImageDraw.Draw(plate)
    for i,(row,boxmask,centermask,oriented) in enumerate(examples):
        x0,y0,x1,y1=row['detector_box'];left=max(0,int(x0)-35);top=max(0,int(y0)-35);right=min(size,int(x1)+36);bottom=min(size,int(y1)+36);y=i*235
        draw.text((8,y+3),row['candidate_id']+' · crops clipped around proposal for display',font=font,fill='#193b36')
        for j,(title,mask) in enumerate((('Original box prompt',boxmask),('Detector-center point',centermask))):
            display=image.copy()
            if mask is not None:display[mask]=(.55*display[mask]+.45*np.array([150,60,230])).astype('uint8')
            # Provisional marks are independent of prompt selection.
            for px,py in points:
                if left<=px<right and top<=py<bottom:cv2.circle(display,(int(px),int(py)),4,(0,220,255),1)
            x=j*340+8;draw.text((x,y+25),title,font=font,fill='#193b36')
            crop=Image.fromarray(cv2.cvtColor(display[top:bottom,left:right],cv2.COLOR_BGR2RGB));crop.thumbnail((320,175));plate.paste(crop,(x,y+45))
        draw.text((690,y+25),'Center-mask oriented crop',font=font,fill='#193b36')
        if oriented is not None:
            crop=Image.fromarray(cv2.cvtColor(oriented,cv2.COLOR_BGR2RGB));crop.thumbnail((220,175));plate.paste(crop,(690,y+45))
        draw.text((930,y+55),'Box crop: '+row['baseline_classifier']['code'],font=font,fill='#193b36')
        draw.text((930,y+85),'Box mask: '+row.get('box_oriented_classifier',{}).get('code','none'),font=font,fill='#193b36')
        draw.text((930,y+115),'Center mask: '+row.get('center_oriented_classifier',{}).get('code','none'),font=font,fill='#193b36')
    plate.save(OUT/'comparison.jpg',quality=90)
    print(json.dumps(summary,indent=2))


if __name__=='__main__':main()
