"""Local DIAMORPH species-model preview on unverified pilot candidates."""
import csv
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 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

ROOT=Path(__file__).resolve().parent.parent
BUNDLE=ROOT/'results/pilot/field-01'
OUT=ROOT/'results/pilot/diamorph-diagnostic'
WEIGHTS=Path('/tmp/diatom-diamorph-species-v2.pt')
TAXA=ROOT/'diatom_pilot/data/diatlas-taxonomic-code.csv'


def preprocess(image, scale_x, scale_y):
    """Follow DIAMORPH square-pad order at 0.1 um/pixel; fail on invalid inputs."""
    if scale_x <= 0 or scale_y <= 0:
        raise ValueError('Physical pixel scales must be positive')
    # Match the author's operation order to avoid half-pixel rounding changes.
    width=max(1,round(image.shape[1]*(scale_x/.1)));height=max(1,round(image.shape[0]*(scale_y/.1)))
    image=cv2.resize(image,(width,height),interpolation=cv2.INTER_AREA)
    if image.shape[0]<image.shape[1]:image=np.transpose(image,(1,0,2))
    y=max(0,(image.shape[0]-512)//2);x=max(0,(image.shape[1]-512)//2)
    image=image[y:y+512,x:x+512]
    image=np.ascontiguousarray(np.flip(image,axis=0))
    canvas=np.full((512,512,3),int(image.mean()),np.uint8)
    return cv2.seamlessClone(image,canvas,np.full_like(image,255),(256,256),cv2.MIXED_CLONE)


def main():
    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()
    taxa={row['taxonomic_code']:row for row in csv.DictReader(TAXA.open(),delimiter=';')}
    missing=[code for code in trained.names.values() if code not in taxa]
    if missing:raise ValueError(f'Unmapped classes: {missing}')
    model=YOLO('yolov8l-cls.yaml',task='classify');model.model=trained
    b=json.loads((BUNDLE/'bundle.json').read_text());OUT.mkdir(parents=True,exist_ok=True)
    scale=b['calibration'];records=[]
    font=ImageFont.truetype('DejaVuSans.ttf',16)
    plate=Image.new('RGB',(1100,len(b['candidates'])*190),'#f8f8f2');draw=ImageDraw.Draw(plate)
    for index,candidate in enumerate(b['candidates'],1):
        image=cv2.imread(str(BUNDLE/candidate['crop']))
        prepared=preprocess(image,scale['x_um_per_pixel'],scale['y_um_per_pixel'])
        name=f'prepared-{index:02d}.png';cv2.imwrite(str(OUT/name),prepared)
        result=model.predict(prepared,imgsz=512,device='cpu',verbose=False)[0]
        scores=result.probs.data.cpu().numpy()
        order=np.argsort(-scores)[:5]
        ranked=[{'code':trained.names[int(i)],'genus':taxa[trained.names[int(i)]]['genus'],
                 'species':taxa[trained.names[int(i)]]['species'],
                 'infra_species':taxa[trained.names[int(i)]]['infra_species'],'score':float(scores[int(i)])} for i in order]
        records.append({'candidate_id':candidate['id'],'source_crop':candidate['crop'],
                        'prepared_image':name,'top_five':ranked})
        original=Image.open(BUNDLE/candidate['crop']).convert('RGB');original.thumbnail((240,150))
        padded=Image.open(OUT/name).convert('RGB');padded.thumbnail((150,150))
        y=(index-1)*190;draw.text((8,y+5),candidate['id'],font=font,fill='#193b36');plate.paste(original,(8,y+30));plate.paste(padded,(270,y+30))
        for j,row in enumerate(ranked[:4]):
            label=row['infra_species'] or row['species'];draw.text((440,y+8+j*34),f"{j+1}. {label} ({row['score']:.3f})",font=font,fill='#193b36')
        print(candidate['id'],[(r['code'],round(r['score'],3)) for r in ranked],flush=True)
    controls=[]
    for gray in (32,128,224):
        blank=preprocess(np.full((128,128,3),gray,np.uint8),scale['x_um_per_pixel'],scale['y_um_per_pixel'])
        result=model.predict(blank,imgsz=512,device='cpu',verbose=False)[0]
        code=trained.names[result.probs.top1]; row=taxa[code]
        controls.append({'gray_value':gray,'top_code':code,'top_species':row['species'],
                         'top_score':float(result.probs.top1conf.cpu())})
    plate.save(OUT/'preview.jpg',quality=90)
    (OUT/'preview.json').write_text(json.dumps({'bundle_id':b['bundle_id'],'model_sha256':hashlib.sha256(WEIGHTS.read_bytes()).hexdigest(),
        'taxonomy_sha256':hashlib.sha256(TAXA.read_bytes()).hexdigest(),'model_class_count':len(trained.names),
        'preprocessing':'DIAMORPH square-pad order, 0.1 µm/pixel, 512 × 512; unverified runtime parity',
        'records':records,'blank_controls':controls},indent=2)+'\n')
    print('Blank controls:', controls, flush=True)


if __name__=='__main__':main()
