"""Compare reference-oriented UDE rectangle crops on previously inspected data."""
import ast
import csv
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 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_ude_diagnostic import normalized

ROOT=Path(__file__).resolve().parent.parent
OUT=ROOT/'results/pilot/diamorph-rectified-controls'
METADATA=Path('/tmp/ude-metadata.csv')


def rectify(image, row):
    points=np.asarray(ast.literal_eval(row['points']),dtype='float32').reshape(-1,2)
    if points.shape!=(4,2):raise ValueError('Expected four rectangle corners')
    points-=np.array([float(row['bbox_x0']),float(row['bbox_y0'])],dtype='float32')
    center,(w,h),angle=cv2.minAreaRect(points)
    if min(w,h)<1:raise ValueError('Degenerate rectangle')
    margin=.05*min(w,h)
    width,height=max(2,round(w+2*margin)),max(2,round(h+2*margin))
    corners=cv2.boxPoints((center,(w+2*margin,h+2*margin),angle)).astype('float32')
    dest=np.array([[0,height-1],[0,0],[width-1,0],[width-1,height-1]],dtype='float32')
    matrix=cv2.getPerspectiveTransform(corners,dest)
    fill=tuple(float(x) for x in np.median(image.reshape(-1,3),axis=0))
    return cv2.warpPerspective(image,matrix,(width,height),flags=cv2.INTER_LINEAR,borderMode=cv2.BORDER_CONSTANT,borderValue=fill)


def main():
    data=json.loads((ROOT/'results/pilot/diamorph-ude-diagnostic/diagnostic.json').read_text())
    wanted={str(r['annotation_id']) for r in data['records']};metadata={}
    with METADATA.open(newline='',encoding='utf-8-sig') as stream:
        for row in csv.DictReader(stream):
            if row['annotation_id'] in wanted:
                if row['annotation_id'] in metadata:raise ValueError('Duplicate annotation id')
                metadata[row['annotation_id']]=row
    if set(metadata)!=wanted:raise ValueError('Missing UDE annotation metadata')
    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):ckpt=torch.load(WEIGHTS,map_location='cpu',weights_only=True)
    import hashlib
    if hashlib.sha256(WEIGHTS.read_bytes()).hexdigest()!=data['model_sha256']:raise ValueError('Model mismatch')
    trained=ckpt['model'].float();model=YOLO('yolov8l-cls.yaml',task='classify');model.model=trained
    taxa={r['taxonomic_code']:r for r in csv.DictReader(TAXA.open(),delimiter=';')}
    records=[];illustrations=[];skipped=[]
    for index,row in enumerate(data['records'],1):
        meta=metadata[str(row['annotation_id'])]
        if meta['shape']!='Rectangle':skipped.append({'annotation_id':row['annotation_id'],'shape':meta['shape']});continue
        original=cv2.imread(str(ROOT/row['image']));rectified=rectify(original,meta)
        outputs={'baseline':row['top_five'][0]}
        # scale-preserving center crop; and a smaller scale that fits all pixels.
        source_scale=.09
        if max(rectified.shape[:2])*.9>512:
            fit_scale=source_scale*(512/(max(rectified.shape[:2])*.9))
        else:fit_scale=source_scale
        variants={'oriented_scale':source_scale,'oriented_fit':fit_scale}
        for name,scale in variants.items():
            prepared=preprocess(rectified,scale,scale)
            result=model.predict(prepared,imgsz=512,device='cpu',verbose=False)[0]
            code=trained.names[int(result.probs.top1)];t=taxa[code]
            outputs[name]={'code':code,'genus':t['genus'],'species':t['species'],'score':float(result.probs.top1conf.cpu())}
        record={'annotation_id':row['annotation_id'],'group':row['group'],'source_genus':row['source_genus'],
                'source_species':row['source_species'],'image':row['image'],'rectified_size_xy':[rectified.shape[1],rectified.shape[0]],
                'known_species':row['source_species_known_exact'],'fit_effective_scale_um_per_pixel':fit_scale,'predictions':outputs}
        records.append(record)
        if len([x for x in illustrations if x[0]['group']==row['group']])<2:
            illustrations.append((record,original,rectified))
        if len(records)%10==0:print('Processed',len(records),'rectangles',flush=True)
    summary={}
    for group in ('gallery_subset','single_slide_prefix','combined'):
        subset=[r for r in records if group=='combined' or r['group']==group]
        g=[r for r in subset if normalized(r['source_genus'])];sp=[r for r in subset if normalized(r['source_species'])]
        summary[group]={'images':len(subset),'genus_labeled':len(g),'species_labeled':len(sp),'variants':{}}
        for variant in ('baseline','oriented_scale','oriented_fit'):
            summary[group]['variants'][variant]={'genus_matches':sum(normalized(r['predictions'][variant]['genus'])==normalized(r['source_genus']) for r in g),
                'species_matches':sum(normalized(r['predictions'][variant]['species'])==normalized(r['source_species']) for r in sp),
                'top_code_changed_vs_baseline':sum(r['predictions'][variant]['code']!=r['predictions']['baseline']['code'] for r in subset)}
    OUT.mkdir(parents=True,exist_ok=True)
    (OUT/'rectified.json').write_text(json.dumps({'method':'reference-oriented rectangles; 5% short-side margin','records':records,
        'skipped':skipped,'summary':summary},indent=2)+'\n')
    font=ImageFont.truetype('DejaVuSans.ttf',16);plate=Image.new('RGB',(1250,len(illustrations)*230),'#f8f8f2');draw=ImageDraw.Draw(plate)
    for i,(row,original,rectified) in enumerate(illustrations):
        y=i*230;draw.text((8,y+4),f"{row['group']} · {row['source_species']} · annotation {row['annotation_id']}",font=font,fill='#193b36')
        for j,image in enumerate((original,rectified)):
            view=Image.fromarray(cv2.cvtColor(image,cv2.COLOR_BGR2RGB));view.thumbnail((280,175),Image.Resampling.LANCZOS);plate.paste(view,(j*300+8,y+32))
        for j,key in enumerate(('baseline','oriented_scale','oriented_fit')):
            v=row['predictions'][key];draw.text((610,y+40+j*45),f"{key}: {v['code']} ({v['score']:.2f})",font=font,fill='#193b36')
    plate.save(OUT/'rectified.jpg',quality=90)
    print(json.dumps(summary,indent=2),flush=True)


if __name__=='__main__':main()
