"""Fit fixed class centroids on train slides; evaluate validation only.

The frozen test split is deliberately not opened. This is closed-set development
on public source cutouts, not a measurement of Academy performance.
"""
import csv
import hashlib
import json
from collections import Counter
from pathlib import Path

import cv2
import numpy as np
import torch
from PIL import Image,ImageDraw,ImageFont
from torchvision.models import resnet18
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 run_field import embedding
from diamorph_preview import WEIGHTS,TAXA,preprocess

ROOT=Path(__file__).resolve().parent.parent
DATA=ROOT/'results/pilot/ude-adaptation-within-genus'
ENCODER=Path('/tmp/resnet18-f37072fd.pth')
OUT=DATA/'centroid-pilot'


def digest(path):return hashlib.sha256(path.read_bytes()).hexdigest()


def unit(v):
    norm=np.linalg.norm(v)
    if not np.isfinite(norm) or norm<=0:raise ValueError('Invalid feature vector')
    return v/norm


def main():
    manifest=DATA/'selection.json';m=json.loads(manifest.read_text());report=json.loads((DATA/'download-report.json').read_text())
    if m.get('design')!='within-genus' or digest(manifest)!=report['selection_sha256'] or report['cross_split_exact_image_duplicates']:
        raise ValueError('Selection or download integrity check failed')
    byid={x['annotation_id']:x for x in report['images']}
    if len(byid)!=len(m['rows']) or len(set(r['filename'] for r in m['rows']))!=len(m['rows']):raise ValueError('Duplicate or missing image entries')
    groups={split:{r['source_slide'] for r in m['rows'] if r['split']==split} for split in ('train','validation','test')}
    if groups['train']&groups['validation'] or groups['train']&groups['test'] or groups['validation']&groups['test']:
        raise ValueError('Source-slide groups overlap')
    # Hash integrity checks include the test files but neither their pixels nor
    # labels are used for feature extraction, fitting or validation.
    for row in m['rows']:
        item=byid.get(row['annotation_id'])
        if item is None or item['split']!=row['split'] or digest(DATA/row['local_file'])!=item['sha256']:raise ValueError('Image integrity mismatch')
    rows=[r for r in m['rows'] if r['split'] in ('train','validation')]
    if Counter(r['split'] for r in rows)!={'train':64,'validation':16}:raise ValueError('Unexpected train/validation size')
    taxa={r['taxonomic_code']:r for r in csv.DictReader(TAXA.open(),delimiter=';')}
    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)
    specialist=checkpoint['model'].float();model=YOLO('yolov8l-cls.yaml',task='classify');model.model=specialist
    labels=m['species']
    restricted={label:[int(i) for i,code in specialist.names.items() if taxa[code]['species']==label] for label in labels}
    if any(len(indices)!=1 for indices in restricted.values()):raise ValueError('Expected one specialist class per study species')
    generic=resnet18(weights=None);generic.load_state_dict(torch.load(ENCODER,map_location='cpu',weights_only=True));generic.fc=torch.nn.Identity();generic.eval()
    captured=[]
    def hook(module,inputs,output):captured.append(output.detach().cpu().numpy().reshape(-1))
    handle=specialist.model[-1].pool.register_forward_hook(hook)
    features=[]
    try:
        for i,row in enumerate(rows,1):
            path=DATA/row['local_file']
            with Image.open(path) as image:generic_feature=embedding(generic,image)
            raw=cv2.imread(str(path));prepared=preprocess(raw,.09,.09)
            captured.clear();prediction=model.predict(prepared,imgsz=512,device='cpu',verbose=False)[0]
            if not captured or len(captured[-1])!=1280:raise ValueError('Unexpected specialist feature shape')
            specialist_feature=unit(captured[-1]);top=trained_code=specialist.names[int(prediction.probs.top1)]
            scores=prediction.probs.data.cpu().numpy()
            restricted_species=max(labels,key=lambda label:float(scores[restricted[label][0]]))
            features.append({'row':row,'generic':generic_feature,'specialist':specialist_feature,
                             'direct_code':top,'direct_species':taxa[top]['species'],'direct_genus':taxa[top]['genus'],
                             'restricted_species':restricted_species})
            if i%10==0:print(f'{i}/{len(rows)} train/validation crops processed',flush=True)
    finally:handle.remove()
    prototypes={}
    for encoder in ('generic','specialist'):
        prototypes[encoder]=np.stack([unit(np.mean([x[encoder] for x in features if x['row']['split']=='train' and x['row']['species']==label],axis=0)) for label in labels])
    records=[]
    for x in features:
        if x['row']['split']!='validation':continue
        row=x['row'];predictions={}
        for encoder in ('generic','specialist'):
            scores=prototypes[encoder]@x[encoder];idx=int(np.argmax(scores))
            predictions[encoder]={'species':labels[idx],'genus':labels[idx].split()[0],'similarity':float(scores[idx])}
        predictions['direct_specialist']={'species':x['direct_species'],'genus':x['direct_genus'],'code':x['direct_code']}
        predictions['restricted_specialist']={'species':x['restricted_species'],'genus':x['restricted_species'].split()[0]}
        records.append({'annotation_id':row['annotation_id'],'source_slide':row['source_slide'],
                        'image':row['local_file'],'species':row['species'],'genus':row['genus'],'predictions':predictions})
    metrics={name:{'top1_species_exact':sum(x['species']==x['predictions'][name]['species'] for x in records),
                   'top1_genus_exact':sum(x['genus']==x['predictions'][name]['genus'] for x in records),
                   'validation_crops':len(records)} for name in ('generic','specialist','direct_specialist','restricted_specialist')}
    OUT.mkdir(parents=True,exist_ok=True)
    np.savez_compressed(OUT/'prototypes.npz',generic=prototypes['generic'],specialist=prototypes['specialist'])
    (OUT/'validation.json').write_text(json.dumps({'selection_sha256':digest(manifest),'generic_weights_sha256':digest(ENCODER),
        'specialist_weights_sha256':digest(WEIGHTS),'labels':labels,'train_crops':64,'validation_crops':16,
        'test_status':'not used for feature extraction, fitting, model selection or scoring',
        'metrics':metrics,'records':records},indent=2)+'\n')
    font=ImageFont.truetype('DejaVuSans.ttf',15);plate=Image.new('RGB',(1150,8*195),'#f8f8f2');draw=ImageDraw.Draw(plate)
    for i,r in enumerate(records[:8]):
        image=Image.open(DATA/r['image']).convert('RGB');image.thumbnail((240,160));y=i*195;plate.paste(image,(8,y+25))
        draw.text((8,y+3),f"Validation image {r['annotation_id']}",font=font,fill='#193b36')
        draw.text((270,y+7),'Dataset: '+r['species'],font=font,fill='#193b36')
        for j,name in enumerate(('generic','specialist','direct_specialist','restricted_specialist')):
            draw.text((270,y+38+j*32),name+': '+r['predictions'][name]['species'],font=font,fill='#193b36')
    plate.save(OUT/'validation-examples.jpg',quality=90)
    print(json.dumps(metrics,indent=2))


if __name__=='__main__':main()
