"""Compare mask-derived versus reference-derived orientations on UDE cutouts.

All model masks are prompted with the complete pre-existing annotated cutout;
this is therefore a conditional crop diagnostic, not automatic field detection.
"""
import argparse
import hashlib
import json
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_preview import WEIGHTS,TAXA,preprocess
from diamorph_rectified_controls import rectify
from diamorph_ude_diagnostic import normalized
import csv

ROOT=Path(__file__).resolve().parent.parent


def mask_crop(image,mask):
    ys,xs=np.where(mask)
    if len(xs)<10:raise ValueError('Mask too small for an oriented crop')
    points=np.column_stack((xs,ys)).astype('float32')
    box=cv2.boxPoints(cv2.minAreaRect(points))
    row={'points':str(box.reshape(-1).tolist()),'bbox_x0':'0','bbox_y0':'0'}
    return rectify(image,row)


def main():
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--prompt',choices=('box','center'),default='box')
    args=parser.parse_args()
    out=ROOT/('results/pilot/diamorph-mask-orientation' if args.prompt=='box' else 'results/pilot/diamorph-mask-center')
    data=json.loads((ROOT/'results/pilot/diamorph-rectified-controls/rectified.json').read_text())
    rows=[r for r in data['records'] if r['group']=='gallery_subset']
    if len(rows)!=18:raise ValueError('Expected the preselected 18-image subset')
    original=json.loads((ROOT/'results/pilot/diamorph-ude-diagnostic/diagnostic.json').read_text())
    model_hash=hashlib.sha256(WEIGHTS.read_bytes()).hexdigest()
    if model_hash!=original['model_sha256']:raise ValueError('Classifier differs from baseline')
    sam_path=Path('/tmp/mobile_sam.pt');sam_hash=hashlib.sha256(sam_path.read_bytes()).hexdigest()
    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
    segmenter=SAM(str(sam_path))
    taxa={r['taxonomic_code']:r for r in csv.DictReader(TAXA.open(),delimiter=';')}
    out.mkdir(parents=True,exist_ok=True);records=[];examples=[]
    for n,row in enumerate(rows,1):
        image=cv2.imread(str(ROOT/row['image']))
        if image is None:raise ValueError('Source crop missing')
        h,w=image.shape[:2]
        prompt={'bboxes':[0,0,w,h]} if args.prompt=='box' else {'points':[[[w//2,h//2]]],'labels':[[1]]}
        pred=segmenter.predict(image,**prompt,imgsz=768,device='cpu',retina_masks=True,verbose=False)[0]
        rec={'annotation_id':row['annotation_id'],'image':row['image'],'source_genus':row['source_genus'],
             'source_species':row['source_species'],'baseline':row['predictions']['baseline'],
             'reference_oriented':row['predictions']['oriented_scale']}
        if pred.masks is None or len(pred.masks.data)!=1:
            rec.update(status='no_single_mask');records.append(rec);continue
        mask=pred.masks.data[0].cpu().numpy().astype(bool)
        if mask.shape!=(h,w):raise ValueError('Mask shape mismatch')
        try:oriented=mask_crop(image,mask)
        except ValueError as exc:
            rec.update(status='invalid_mask',error=str(exc));records.append(rec);continue
        prepared=preprocess(oriented,.09,.09)
        result=classifier.predict(prepared,imgsz=512,device='cpu',verbose=False)[0]
        code=trained.names[int(result.probs.top1)];meta=taxa[code]
        rec.update(status='ok',mask_area=int(mask.sum()),mask_fraction=float(mask.mean()),
                   mask_oriented={'code':code,'genus':meta['genus'],'species':meta['species'],
                                  'score':float(result.probs.top1conf.cpu())})
        records.append(rec)
        if len(examples)<4:examples.append((rec,image,mask,oriented))
        print(n,row['annotation_id'],'mask area',round(float(mask.mean()),3),'class',code,flush=True)
    summary={}
    genus=[r for r in records if normalized(r['source_genus'])]
    species=[r for r in records if normalized(r['source_species'])]
    for method in ('baseline','reference_oriented','mask_oriented'):
        def match(r,key):return method in r and normalized(r[method][key])==normalized(r['source_'+key])
        summary[method]={'genus_matches':sum(match(r,'genus') for r in genus),'genus_labeled':len(genus),
                         'species_matches':sum(match(r,'species') for r in species),'species_labeled':len(species)}
    (out/'diagnostic.json').write_text(json.dumps({'method':f'SAM {args.prompt} prompt on labeled cutout; mask-derived minimum-area crop',
        'classifier_sha256':model_hash,'segmenter_sha256':sam_hash,'summary':summary,'records':records},indent=2)+'\n')
    font=ImageFont.truetype('DejaVuSans.ttf',15);plate=Image.new('RGB',(1200,len(examples)*210),'#f8f8f2');draw=ImageDraw.Draw(plate)
    for i,(row,image,mask,oriented) in enumerate(examples):
        h,w=image.shape[:2];overlay=image.copy();overlay[mask]=(.55*overlay[mask]+.45*np.array([150,60,230])).astype('uint8')
        views=[('Source cutout',image),(f'Mask from {args.prompt} prompt',overlay),('Mask-oriented crop',oriented)]
        y=i*210;draw.text((8,y+3),f"{row['annotation_id']} · dataset label {row['source_species']}",font=font,fill='#193b36')
        for j,(title,array) in enumerate(views):
            x=j*300+8;draw.text((x,y+25),title,font=font,fill='#193b36');display=Image.fromarray(cv2.cvtColor(array,cv2.COLOR_BGR2RGB));display.thumbnail((280,150));plate.paste(display,(x,y+50))
        for j,key in enumerate(('baseline','reference_oriented','mask_oriented')):
            draw.text((910,y+35+j*42),f"{key}: {row[key]['code']}",font=font,fill='#193b36')
    plate.save(out/'comparison.jpg',quality=90)
    print(json.dumps(summary,indent=2),flush=True)


if __name__=='__main__':main()
