"""Score held-out labeled crops with a frozen centroid protocol, not field detection."""
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 mask_features import masked_image,mask_bounds_crop
from run_field import embedding
from train_centroids import unit


def main():
    p=argparse.ArgumentParser(description=__doc__);p.add_argument('--dataset',type=Path,required=True)
    p.add_argument('--model',type=Path,required=True);p.add_argument('--encoder',type=Path,required=True)
    p.add_argument('--protocol',type=Path,required=True);p.add_argument('--output',type=Path,required=True);a=p.parse_args()
    dataset_file=a.dataset/'dataset.json';model_file=a.model/'model.json';centroid_file=a.model/'centroids.npz'
    data=json.loads(dataset_file.read_text());model=json.loads(model_file.read_text());protocol=json.loads(a.protocol.read_text())
    rank=model.get('label_rank','species');threshold=protocol.get('threshold')
    if (data.get('format')!='diatom-classifier-data-v1' or model.get('format')!='diatom-centroid-classifier-v1'
        or protocol.get('format')!='diatom-centroid-frozen-protocol-v1' or rank not in {'genus','species'}
        or data.get('label_rank','species')!=rank or protocol.get('rank')!=rank):raise ValueError('Incompatible dataset, model or protocol')
    if (not isinstance(threshold,(int,float)) or isinstance(threshold,bool) or not math.isfinite(threshold) or not -1<=threshold<=1
        or protocol.get('threshold_rule')!='accept if cosine similarity >= threshold' or protocol.get('threshold_source')!='declared_validation_report'):
        raise ValueError('Invalid frozen threshold')
    for key,actual in [('model_sha256',digest(model_file)),('centroids_sha256',digest(centroid_file)),('dataset_sha256',digest(dataset_file)),('encoder_sha256',digest(a.encoder))]:
        if protocol.get(key)!=actual:raise ValueError(f'Frozen {key} mismatch')
    if model.get('dataset_sha256')!=protocol['dataset_sha256'] or model.get('encoder_sha256')!=protocol['encoder_sha256'] or model.get('centroids_sha256')!=protocol['centroids_sha256']:
        raise ValueError('Model provenance mismatch')
    labels=model['labels'];mode=model.get('crop_mode','raw');framing=model.get('crop_framing','legacy')
    if not isinstance(labels,list) or len(labels)<2 or len(set(labels))!=len(labels) or mode not in {'raw','masked'} or framing not in {'legacy','mask_bounds_8'}:raise ValueError('Invalid model')
    with np.load(centroid_file,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 centroids')
    rows=data.get('rows')
    if not isinstance(rows,list):raise ValueError('Invalid dataset rows')
    samples={};slides={};field_splits={};image_splits={};test=[];test_ids=set()
    for row in rows:
        split=row.get('split');sample=row.get('sample_id');slide=row.get('slide');field_hash=row.get('source_field_sha256');image_hash=row.get('image_sha256')
        if (split not in {'train','validation','test'} or not isinstance(sample,str) or not sample or not isinstance(slide,str) or not slide
            or Path(slide).name!=slide or not isinstance(field_hash,str) or len(field_hash)!=64 or not isinstance(image_hash,str) or len(image_hash)!=64):raise ValueError('Missing split or provenance')
        if sample in samples and samples[sample]!=split:raise ValueError('Sample crosses splits')
        if slide in slides and slides[slide]!=sample:raise ValueError('Slide has inconsistent sample IDs')
        if field_hash in field_splits and field_splits[field_hash]!=split:raise ValueError('Source field crosses splits')
        if image_hash in image_splits and image_splits[image_hash]!=split:raise ValueError('Crop crosses splits')
        samples[sample]=split;slides[slide]=sample;field_splits[field_hash]=split;image_splits[image_hash]=split
        if split=='test':
            if row.get('adjudicated') is not True or row.get('adjudicator_role')!='expert' or not row.get('adjudication_sha256') or not row.get('adjudication_protocol_id'):
                raise ValueError('Test crops must carry declared expert adjudication provenance')
            if not isinstance(row.get('bundle_id'),str) or not row['bundle_id'] or not isinstance(row.get('specimen_id'),str) or not row['specimen_id']:raise ValueError('Test crop lacks specimen or bundle provenance')
            identity=(row['bundle_id'],row['specimen_id'])
            if identity in test_ids:raise ValueError('Duplicate held-out specimen identity')
            test_ids.add(identity)
            label=row.get(rank)
            if not isinstance(label,str) or not label or label!=label.strip():raise ValueError('Test crop lacks explicit rank label')
            test.append(row)
    if (len(test)!=model.get('held_out_test_rows') or sorted({r['sample_id'] for r in test})!=model.get('held_out_test_samples')
        or sorted({r['bundle_id'] for r in test})!=model.get('held_out_test_bundle_ids')
        or sorted({r['slide'] for r in test})!=model.get('held_out_test_slides') or not test):raise ValueError('Held-out membership differs from frozen model')
    if a.output.exists() and any(a.output.iterdir()):raise FileExistsError('Output directory must be empty')
    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()
    predictions=[]
    for row in test:
        image_path=inside(a.dataset,row.get('image'))
        if digest(image_path)!=row['image_sha256']:raise ValueError('Held-out crop hash mismatch')
        with Image.open(image_path) as image:
            if mode=='masked' or framing=='mask_bounds_8':
                mask_path=inside(a.dataset,row.get('mask'))
                if digest(mask_path)!=row.get('mask_sha256'):raise ValueError('Held-out mask hash mismatch')
                with Image.open(mask_path) as mask:
                    if framing=='mask_bounds_8':image,mask,_=mask_bounds_crop(image,mask)
                    if mode=='masked':image=masked_image(image,mask)
                    vector=unit(embedding(encoder,image))
            else:vector=unit(embedding(encoder,image))
        scores=centroids@vector;i=int(np.argmax(scores));score=float(scores[i]);accepted=score>=threshold
        predictions.append({'sample_id':row['sample_id'],'bundle_id':row['bundle_id'],'specimen_id':row['specimen_id'],
                            'true_label':row[rank],'nearest_label':labels[i],'similarity':score,'accepted':accepted,
                            'correct':accepted and labels[i]==row[rank],'truth_in_training_vocabulary':row[rank] in labels})
    correct=sum(x['correct'] for x in predictions);accepted=sum(x['accepted'] for x in predictions)
    result={'format':'diatom-centroid-crop-test-v1','rank':rank,'protocol_sha256':digest(a.protocol),'model_sha256':digest(model_file),
            'dataset_sha256':digest(dataset_file),'threshold':threshold,'test_samples':len({x['sample_id'] for x in predictions}),
            'eligible_crops':len(predictions),'accepted':accepted,'correct':correct,'abstained':len(predictions)-accepted,
            'correct_over_all_crops':correct/len(predictions),'correct_over_accepted':correct/accepted if accepted else None,
            'unseen_truth':sum(not x['truth_in_training_vocabulary'] for x in predictions),
            'unseen_accepted':sum(not x['truth_in_training_vocabulary'] and x['accepted'] for x in predictions),
            'predictions':predictions,'warning':'Preselected crops only, not end-to-end identification or detection. Protocol and expert/sample declarations are not verified; test reuse invalidates independence.'}
    a.output.mkdir(parents=True,exist_ok=True)
    with (a.output/'result.json').open('x') as f:json.dump(result,f,indent=2);f.write('\n')
    print(f'Scored {len(predictions)} held-out crops. This does not establish end-to-end accuracy.')


if __name__=='__main__':main()
