"""Generate review-only closed-set centroid suggestions for a field bundle."""
import argparse
import json
import math
from pathlib import Path

import numpy as np
import torch
from PIL import Image
from torchvision.models import resnet18

from ingest_review import digest,inside
from run_field import embedding
from train_centroids import unit
from mask_features import masked_image,crop_field_mask,mask_bounds_crop


def main():
    p=argparse.ArgumentParser(description=__doc__);p.add_argument('--bundle',type=Path,required=True)
    p.add_argument('--model',type=Path,required=True);p.add_argument('--encoder',type=Path,required=True)
    p.add_argument('--sample-id',required=True,help='Biological sample ID, not slide ID')
    p.add_argument('--species-threshold',type=float,help='Explicit development-selected minimum cosine similarity')
    p.add_argument('--genus-threshold',type=float,help='Explicit development-selected minimum genus similarity')
    a=p.parse_args();bundle=json.loads((a.bundle/'bundle.json').read_text());model=json.loads((a.model/'model.json').read_text())
    if any(x is not None and (not math.isfinite(x) or not -1<=x<=1) for x in (a.species_threshold,a.genus_threshold)):
        p.error('Thresholds must be finite and between -1 and 1')
    if a.species_threshold is not None and a.genus_threshold is not None and a.genus_threshold>a.species_threshold:
        p.error('Genus threshold cannot exceed species threshold for this shared similarity score')
    rank=model.get('label_rank','species')
    if rank not in {'species','genus'}:raise ValueError('Invalid classifier rank')
    out=a.bundle/('centroid-genus-suggestions.json' if rank=='genus' else 'centroid-suggestions.json')
    if out.exists():raise FileExistsError('Centroid suggestions already exist')
    other=a.bundle/('centroid-suggestions.json' if rank=='genus' else 'centroid-genus-suggestions.json')
    if other.exists():
        existing=json.loads(other.read_text())
        if existing.get('bundle_id')!=bundle['bundle_id'] or existing.get('sample_id')!=a.sample_id:
            raise ValueError('Existing centroid suggestions have a different field or sample ID')
        if existing.get('label_rank','species')==rank:raise ValueError('Suggestions for this rank already exist in the other manifest')
    if (model.get('format')!='diatom-centroid-classifier-v1' or not isinstance(model.get('held_out_test_samples'),list)
        or not isinstance(model.get('held_out_test_bundle_ids'),list) or not isinstance(model.get('held_out_test_slides'),list)):
        raise ValueError('Model lacks held-out sample or slide provenance; regenerate it')
    if not a.sample_id or a.sample_id!=a.sample_id.strip():raise ValueError('Invalid sample ID')
    if a.sample_id in model['held_out_test_samples'] or bundle['bundle_id'] in model['held_out_test_bundle_ids'] or bundle['slide'] in model['held_out_test_slides']:
        raise ValueError('Refusing to score a declared held-out test sample or field')
    if digest(a.encoder)!=model['encoder_sha256'] or digest(a.model/'centroids.npz')!=model['centroids_sha256']:raise ValueError('Model or encoder hash mismatch')
    labels=model['labels']
    crop_mode=model.get('crop_mode','raw');crop_framing=model.get('crop_framing','legacy')
    if crop_mode not in {'raw','masked'} or crop_framing not in {'legacy','mask_bounds_8'}:raise ValueError('Invalid model crop mode or framing')
    if not isinstance(labels,list) or len(labels)<2 or len(set(labels))!=len(labels) or any(not isinstance(x,str) or not x for x in labels):raise ValueError('Invalid class vocabulary')
    mapping=model.get('species_to_genus')
    if mapping is not None and (not isinstance(mapping,dict) or set(mapping)!=set(labels) or any(not isinstance(v,str) or not v or v!=v.strip() for v in mapping.values())):
        raise ValueError('Invalid species-to-genus mapping')
    if a.genus_threshold is not None and rank=='species' and not mapping:raise ValueError('Genus threshold requires a taxonomy map')
    if rank=='genus' and a.species_threshold is not None:raise ValueError('Genus-only model cannot use a species threshold')
    with np.load(a.model/'centroids.npz',allow_pickle=False) as archive:centroids=archive['vectors']
    if centroids.shape!=(len(labels),512) or not np.isfinite(centroids).all() or not np.allclose(np.linalg.norm(centroids,axis=1),1,atol=1e-4):raise ValueError('Invalid centroid matrix')
    candidates=list(bundle['candidates']);manifests={}
    for filename,fmt,key in [('split-alternatives.json','diatom-split-alternatives-v1','hypotheses'),('tile-proposals.json','diatom-tile-proposals-v1','proposals'),('stack-proposals.json','diatom-stack-proposals-v1','proposals')]:
        path=a.bundle/filename
        if not path.exists():continue
        data=json.loads(path.read_text())
        if data.get('format')!=fmt or data.get('bundle_id')!=bundle['bundle_id'] or not isinstance(data.get(key),list):raise ValueError(f'Invalid {filename}')
        candidates.extend(data[key]);manifests[filename]=digest(path)
    if len({x['id'] for x in candidates})!=len(candidates):raise ValueError('Duplicate candidate IDs')
    torch.set_num_threads(4);encoder=resnet18(weights=None);encoder.load_state_dict(torch.load(a.encoder,map_location='cpu',weights_only=True));encoder.fc=torch.nn.Identity();encoder.eval()
    rows=[];frames={};focus_data=None
    def source_plane(z):
        nonlocal focus_data
        if z in frames:return frames[z]
        if z==bundle['z']:source=inside(a.bundle,bundle['field_image'])
        else:
            if focus_data is None:
                focus_path=a.bundle/'focus-planes.json';focus_data=json.loads(focus_path.read_text())
                if focus_data.get('format')!='diatom-focus-planes-v1' or focus_data.get('bundle_id')!=bundle['bundle_id'] or not isinstance(focus_data.get('planes'),list):raise ValueError('Invalid focal-plane manifest')
                manifests['focus-planes.json']=digest(focus_path)
            selected=[x for x in focus_data['planes'] if x.get('z')==z]
            if len(selected)!=1:raise ValueError('Candidate focal plane is absent or repeated')
            source=inside(a.bundle,selected[0]['image'])
            if digest(source)!=selected[0].get('sha256'):raise ValueError('Candidate focal plane hash mismatch')
        with Image.open(source) as image:frame=image.convert('RGB')
        if frame.size!=(bundle['size'],bundle['size']):raise ValueError('Invalid candidate focal-plane dimensions')
        frames[z]=(frame,digest(source));return frames[z]
    for candidate in candidates:
        path=inside(a.bundle,candidate['crop'])
        mask_hash=None;skip=None;input_box=None;source_hash=None
        with Image.open(path) as image:
            if crop_mode=='masked' or crop_framing=='mask_bounds_8':
                if not candidate.get('mask'):skip='no_model_mask'
                else:
                    mask_path=inside(a.bundle,candidate['mask']);mask_hash=digest(mask_path)
                    with Image.open(mask_path) as mask:
                        if mask.size!=(bundle['size'],bundle['size']):raise ValueError('Candidate mask dimensions mismatch')
                        if crop_framing=='mask_bounds_8':
                            if not mask.convert('L').getbbox():skip='empty_model_mask'
                            else:
                                frame,source_hash=source_plane(candidate.get('plane_z',bundle['z']))
                                image,crop_mask,input_box=mask_bounds_crop(frame,mask)
                        else:crop_mask=crop_field_mask(mask,candidate['box'],bundle['size'],image.size)
                        if not skip:
                            if not crop_mask.convert('L').getbbox():skip='empty_mask_in_crop'
                            else:
                                if crop_mode=='masked':image=masked_image(image,crop_mask)
                                vector=unit(embedding(encoder,image))
            else:vector=unit(embedding(encoder,image))
        if skip:
            rows.append({'candidate_id':candidate['id'],'source_crop':candidate['crop'],'source_crop_sha256':digest(path),
                         'source_mask_sha256':mask_hash,'skip_reason':skip,'suggestions':[],'genus_suggestions':[],
                         'species_decision':'unavailable','genus_decision':'unavailable','accepted_species':None,'accepted_genus':None});continue
        scores=centroids@vector;order=np.argsort(-scores)[:min(5,len(labels))]
        genus_scores={}
        if rank=='genus':
            genus_scores={label:float(score) for label,score in zip(labels,scores)}
        elif mapping:
            for label,score in zip(labels,scores):
                genus=mapping[label];genus_scores[genus]=max(genus_scores.get(genus,float('-inf')),float(score))
        genus_ranked=sorted(genus_scores.items(),key=lambda item:(-item[1],item[0]))[:5]
        best_species=labels[int(order[0])];best_score=float(scores[int(order[0])])
        species_decision=('unavailable' if rank=='genus' else ('not_configured' if a.species_threshold is None else ('accepted' if best_score>=a.species_threshold else 'abstained')))
        genus_decision=('unavailable' if not genus_ranked else ('not_configured' if a.genus_threshold is None else ('accepted' if genus_ranked[0][1]>=a.genus_threshold else 'abstained')))
        rows.append({'candidate_id':candidate['id'],'source_crop':candidate['crop'],'source_crop_sha256':digest(path),
                     'source_mask_sha256':mask_hash,'source_plane_sha256':source_hash,'input_bbox_xyxy':input_box,'skip_reason':None,
                     'species_decision':species_decision,'accepted_species':best_species if species_decision=='accepted' else None,
                     'genus_decision':genus_decision,'accepted_genus':genus_ranked[0][0] if genus_decision=='accepted' else None,
                     'genus_suggestions':[{'genus':name,'similarity':score} for name,score in genus_ranked],
                     'suggestions':[{'species':labels[int(i)],'similarity':float(scores[int(i)])} for i in order] if rank=='species' else []})
    result={'format':'diatom-centroid-suggestions-v1','bundle_id':bundle['bundle_id'],'sample_id':a.sample_id,
            'model_sha256':digest(a.model/'model.json'),'centroids_sha256':model['centroids_sha256'],
            'encoder_sha256':model['encoder_sha256'],'source_manifests_sha256':manifests,
            'training_species_count':len(labels) if rank=='species' else 0,'training_label_count':len(labels),'label_rank':rank,
            'provisional_training':model['provisional_used'],'crop_mode':crop_mode,'crop_framing':crop_framing,
            'species_threshold':a.species_threshold,'genus_threshold':a.genus_threshold,
            'taxonomy_version':model.get('taxonomy_version'),'taxonomy_sha256':model.get('taxonomy_sha256'),'records':rows,
            'warning':'Closed-set development suggestions; similarity is not a probability and unknown species are not rejected. Sample identity is user-supplied.'}
    with out.open('x') as f:json.dump(result,f,indent=2);f.write('\n')
    print(f'Wrote suggestions for {len(rows)} candidates; all names remain unresolved.')


if __name__=='__main__':main()
