"""Run DIAMORPH on six fixed source-atlas images; not independent testing."""
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

from diamorph_preview import WEIGHTS,TAXA,preprocess

ROOT=Path(__file__).resolve().parent.parent
MANIFEST=Path('/tmp/diatom-diatlas-controls/selection.json')
OUT=ROOT/'results/pilot/diamorph-atlas-controls'


def main():
    rows=json.loads(MANIFEST.read_text())['rows']
    if len(rows)!=6:raise ValueError('Expected six selected atlas controls')
    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)
    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=';')}
    OUT.mkdir(parents=True,exist_ok=True);records=[]
    font=ImageFont.truetype('DejaVuSans.ttf',15)
    sheet=Image.new('RGB',(1100,len(rows)*205),'#f8f8f2');draw=ImageDraw.Draw(sheet)
    for index,row in enumerate(rows,1):
        path=Path(row['local_file'])
        if hashlib.sha256(path.read_bytes()).hexdigest()!=row['sha256']:raise ValueError('Control image hash mismatch')
        image=cv2.imread(str(path));scale=float(row['scale_um_per_pixel'])
        if image is None or not .01<=scale<=1:raise ValueError('Missing image or unreasonable physical scale')
        prepared=preprocess(image,scale,scale)
        # The upstream square-pad script writes grayscale, even for color atlas sources.
        gray=cv2.cvtColor(prepared,cv2.COLOR_BGR2GRAY)
        model_input=cv2.cvtColor(gray,cv2.COLOR_GRAY2BGR)
        result=model.predict(model_input,imgsz=512,device='cpu',verbose=False)[0]
        probs=result.probs.data.cpu().numpy();top=np.argsort(-probs)[:5]
        ranked=[{'code':trained.names[int(i)],'species':taxa[trained.names[int(i)]]['species'],
                 'genus':taxa[trained.names[int(i)]]['genus'],'score':float(probs[int(i)])} for i in top]
        code=row['species_code'];expected=taxa[code]
        record={'expected_code':code,'expected_species':expected['species'],'source':row['source'],'page':row['page'],
                'zip_member':row['zip_member'],'image_sha256':row['sha256'],'scale_um_per_pixel':scale,'top_five':ranked}
        records.append(record)
        original=Image.open(path).convert('RGB');original.thumbnail((250,150),Image.Resampling.LANCZOS)
        image2=Image.fromarray(gray);image2.thumbnail((150,150),Image.Resampling.LANCZOS)
        y=(index-1)*205;sheet.paste(original,(8,y+35));sheet.paste(image2.convert('RGB'),(280,y+35))
        draw.text((8,y+6),f'{code} · {expected["species"]}',font=font,fill='#193b36')
        for j,r in enumerate(ranked[:4]):draw.text((460,y+10+j*34),f"{j+1}. {r['code']} · {r['species']} ({r['score']:.3f})",font=font,fill='#193b36')
        print(code,'→',[(r['code'],round(r['score'],3)) for r in ranked],flush=True)
    summary={'controls':len(records),'top1_code_matches':sum(r['top_five'][0]['code']==r['expected_code'] for r in records),
             'top5_code_matches':sum(any(x['code']==r['expected_code'] for x in r['top_five']) for r in records)}
    (OUT/'controls.json').write_text(json.dumps({'model_sha256':hashlib.sha256(WEIGHTS.read_bytes()).hexdigest(),
        'atlas_index_md5':'be2fc6d2ee5b568869725852e340dd1a','summary':summary,'records':records},indent=2)+'\n')
    sheet.save(OUT/'controls.jpg',quality=90)
    print(json.dumps(summary,indent=2))


if __name__=='__main__':main()
