"""Score original field proposals under a frozen protocol; do not match references."""
import argparse
import hashlib
import json
import math
from pathlib import Path

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

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


def main():
    p=argparse.ArgumentParser(description=__doc__)
    p.add_argument('--protocol',type=Path,required=True);p.add_argument('--field-id',required=True)
    p.add_argument('--bundle',type=Path,required=True);p.add_argument('--encoder',type=Path,required=True)
    for rank in ('genus','species'):p.add_argument('--'+rank+'-model',type=Path)
    p.add_argument('--output',type=Path,required=True);a=p.parse_args()
    protocol=json.loads(a.protocol.read_text());bundle_file=a.bundle/'bundle.json';bundle=json.loads(bundle_file.read_text())
    fields=protocol.get('fields');classifiers=protocol.get('classifiers');config=protocol.get('detector_configuration')
    policies={'all_original_detector_candidates'+('_plus_tile' if tile else '')+('_plus_stack' if stack else '')+('_plus_split' if split else '')
              for tile in (False,True) for stack in (False,True) for split in (False,True)}
    if (protocol.get('format')!='diatom-frozen-field-protocol-v1' or protocol.get('candidate_policy') not in policies
        or not isinstance(fields,list) or not isinstance(classifiers,dict) or not classifiers or not isinstance(config,dict)):
        raise ValueError('Invalid frozen field protocol')
    if protocol.get('scoring_environment')!=snapshot(protocol['candidate_policy']):
        raise ValueError('Frozen scoring code or environment mismatch; inspect the protocol and restore the recorded environment')
    fields=[f for f in fields if isinstance(f,dict) and f.get('id')==a.field_id]
    if len(fields)!=1:raise ValueError('Field ID is absent or repeated in frozen protocol')
    field=fields[0]
    if (bundle.get('format')!='diatom-field-bundle-v1' or bundle.get('slide')!=field.get('slide')
        or bundle.get('origin_xy')!=field.get('origin_xy') or bundle.get('z')!=field.get('z') or bundle.get('size')!=field.get('size')
        or (field.get('slide_size_bytes') is not None and bundle.get('slide_size_bytes')!=field['slide_size_bytes'])
        or bundle.get('size')!=config.get('field_size') or bundle.get('models')!=config.get('models')
        or bundle.get('detector_confidence')!=config.get('detector_confidence') or bundle.get('max_candidates')!=config.get('max_candidates')):
        raise ValueError('Field or detector configuration does not match frozen protocol')
    unsigned={k:v for k,v in bundle.items() if k!='bundle_id'}
    if hashlib.sha256(json.dumps(unsigned,sort_keys=True).encode()).hexdigest()!=bundle.get('bundle_id'):raise ValueError('Field bundle identity mismatch')
    encoder_hash=digest(a.encoder);models={}
    for rank in ('genus','species'):
        frozen=classifiers.get(rank);directory=getattr(a,rank+'_model')
        if bool(frozen)!=bool(directory):raise ValueError(f'Provide exactly the frozen {rank} model')
        if not frozen:continue
        model_file=directory/'model.json';model=json.loads(model_file.read_text());centroids_file=directory/'centroids.npz';threshold=frozen.get('threshold')
        if (model.get('format')!='diatom-centroid-classifier-v1' or model.get('label_rank','species')!=rank
            or digest(model_file)!=frozen.get('model_sha256') or digest(centroids_file)!=frozen.get('centroids_sha256')
            or encoder_hash!=frozen.get('encoder_sha256') or model.get('encoder_sha256')!=encoder_hash
            or model.get('centroids_sha256')!=frozen.get('centroids_sha256') or model.get('crop_mode','raw')!=frozen.get('crop_mode')
            or model.get('crop_framing','legacy')!=frozen.get('crop_framing','legacy')
            or frozen.get('crop_mode') not in {'raw','masked'} or frozen.get('crop_framing','legacy') not in {'legacy','mask_bounds_8'}
            or type(threshold) not in (float,int) or not math.isfinite(threshold) or not -1<=threshold<=1):raise ValueError(f'Frozen {rank} model mismatch')
        labels=model.get('labels')
        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 classifier labels')
        with np.load(centroids_file,allow_pickle=False) as archive:vectors=archive['vectors']
        if vectors.shape!=(len(labels),512) or not np.isfinite(vectors).all() or not np.allclose(np.linalg.norm(vectors,axis=1),1,atol=1e-4):raise ValueError('Invalid centroid vectors')
        models[rank]=(frozen,labels,vectors)
    original=bundle.get('candidates')
    if not isinstance(original,list) or len(original)>config['max_candidates']:raise ValueError('Invalid detector candidates')
    candidates=[dict(c,plane_z=bundle['z'],proposal_source='original') for c in original];proposal_hashes={}
    settings=protocol.get('optional_proposal_settings',{});policy=protocol['candidate_policy']
    if not isinstance(settings,dict):raise ValueError('Invalid optional proposal settings')
    expected_names=({'tile-proposals.json'} if '_plus_tile' in policy else set())|({'stack-proposals.json'} if '_plus_stack' in policy else set())|({'split-alternatives.json'} if '_plus_split' in policy else set())
    if set(settings)!=expected_names:raise ValueError('Optional proposal settings do not match frozen policy')
    for enabled,name,fmt,source,entries in [('_plus_tile' in policy,'tile-proposals.json','diatom-tile-proposals-v1','tile_hypothesis','proposals'),
                                    ('_plus_stack' in policy,'stack-proposals.json','diatom-stack-proposals-v1','stack_track','proposals'),
                                    ('_plus_split' in policy,'split-alternatives.json','diatom-split-alternatives-v1','split_hypothesis','hypotheses')]:
        if not enabled:
            if name in settings:raise ValueError('Unexpected optional proposal settings')
            continue
        expected=settings.get(name);path=a.bundle/name;manifest=json.loads(path.read_text())
        required=({'tile_hypothesis':('tile_size','stride','detector_input','confidence','nms_iou','max_proposals'),
                   'stack_track':('source','link_iou','max_z_gap'),
                   'split_hypothesis':('method','area_range','minimum_mask_score','duplicate_iou')})[source]
        if (not isinstance(expected,dict) or set(expected)!=set(required) or manifest.get('format')!=fmt or manifest.get('bundle_id')!=bundle['bundle_id']
            or not isinstance(manifest.get(entries),list) or any(manifest.get(k)!=expected[k] for k in required)
            or (source=='tile_hypothesis' and manifest.get('plane_z')!=bundle['z'])
            or (source=='tile_hypothesis' and (type(expected['max_proposals']) is not int or len(manifest['proposals'])>expected['max_proposals']))
            or (source=='stack_track' and manifest.get('plane_counts') is None)):raise ValueError(f'Frozen settings mismatch: {name}')
        for c in manifest[entries]:
            if not isinstance(c,dict) or c.get('source')!=source:raise ValueError(f'Invalid proposal source: {name}')
            if source in {'tile_hypothesis','split_hypothesis'} and c.get('plane_z',bundle['z'])!=bundle['z']:raise ValueError('Proposal has an unexpected source plane')
            if source=='split_hypothesis' and c.get('parent_candidate_id') not in {x.get('id') for x in original}:raise ValueError('Split proposal has an unknown parent')
            candidates.append(dict(c,plane_z=c.get('plane_z',bundle['z']),proposal_source=source))
        proposal_hashes[name]=digest(path)
    image_file=inside(a.bundle,bundle['field_image']);image_hash=digest(image_file)
    with Image.open(image_file) as im:field_image=im.convert('RGB')
    if field_image.size!=(bundle['size'],bundle['size']):raise ValueError('Invalid field dimensions')
    frames={bundle['z']:(field_image,image_hash)}
    if '_plus_stack' in policy:
        focus_file=a.bundle/'focus-planes.json';focus=json.loads(focus_file.read_text())
        if focus.get('format')!='diatom-focus-planes-v1' or focus.get('bundle_id')!=bundle['bundle_id'] or not isinstance(focus.get('planes'),list):raise ValueError('Invalid focal stack')
        seen_planes=set()
        for plane in focus['planes']:
            z=plane.get('z')
            if type(z) is not int or z<0 or z in seen_planes:raise ValueError('Invalid focal plane')
            seen_planes.add(z);path=inside(a.bundle,plane['image'])
            if digest(path)!=plane.get('sha256'):raise ValueError('Focal plane hash mismatch')
            with Image.open(path) as im:frame=im.convert('RGB')
            if frame.size!=field_image.size or (z==bundle['z'] and ImageChops.difference(frame,field_image).getbbox()):raise ValueError('Focal plane dimensions or pixels mismatch')
            frames[z]=(frame,digest(path))
        if bundle['z'] not in seen_planes:raise ValueError('Detector plane absent from focal stack')
        proposal_hashes['focus-planes.json']=digest(focus_file)
    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=[];ids=set()
    for candidate in candidates:
        ident=candidate.get('id');box=candidate.get('box');z=candidate.get('plane_z')
        if (not isinstance(ident,str) or not ident or ident in ids or not isinstance(box,list) or len(box)!=4
            or any(type(x) not in (int,float) or not math.isfinite(x) for x in box) or type(z) is not int or z not in frames):raise ValueError('Invalid candidate identity, box or focal plane')
        ids.add(ident);x0,y0,x1,y1=box;cropbox=(max(0,math.floor(x0)),max(0,math.floor(y0)),min(bundle['size'],math.ceil(x1)),min(bundle['size'],math.ceil(y1)))
        if cropbox[0]>=cropbox[2] or cropbox[1]>=cropbox[3]:raise ValueError('Invalid candidate crop bounds')
        path=inside(a.bundle,candidate['crop'])
        with Image.open(path) as im:crop=im.convert('RGB')
        if crop.size!=(cropbox[2]-cropbox[0],cropbox[3]-cropbox[1]) or ImageChops.difference(crop,frames[z][0].crop(cropbox)).getbbox():raise ValueError('Candidate crop does not match its focal plane')
        mask_path=inside(a.bundle,candidate['mask']) if candidate.get('mask') else None;full_mask=None
        if mask_path:
            with Image.open(mask_path) as mask:
                if mask.size!=(bundle['size'],bundle['size']):raise ValueError('Invalid candidate mask dimensions')
                full_mask=mask.convert('L')
        row={'id':ident,'box':box,'plane_z':z,'proposal_source':candidate['proposal_source'],'source_plane_sha256':frames[z][1],
             'parent_candidate_id':candidate.get('parent_candidate_id'),
             'crop':candidate['crop'],'source_crop_sha256':digest(path),
             'mask':candidate.get('mask'),'source_mask_sha256':digest(mask_path) if mask_path else None,
             'mask_status':'missing' if full_mask is None else ('nonempty' if full_mask.getbbox() else 'empty'),
             'genus':None,'species':None,'scores':{}}
        vectors_by_mode={}
        for rank,(frozen,labels,centroids) in models.items():
            mode=frozen['crop_mode'];framing=frozen.get('crop_framing','legacy');cache_key=(mode,framing)
            if cache_key not in vectors_by_mode:
                if (mode=='masked' or framing=='mask_bounds_8') and (full_mask is None or not full_mask.getbbox()):
                    vectors_by_mode[cache_key]=(None,None)
                else:
                    input_image=crop;input_mask=None;input_box=cropbox
                    if framing=='mask_bounds_8':input_image,input_mask,input_box=mask_bounds_crop(frames[z][0],full_mask)
                    elif mode=='masked':input_mask=crop_field_mask(full_mask,box,bundle['size'],crop.size)
                    if mode=='masked' and not input_mask.getbbox():vectors_by_mode[cache_key]=(None,None)
                    else:
                        if mode=='masked':input_image=masked_image(input_image,input_mask)
                        vectors_by_mode[cache_key]=(unit(embedding(encoder,input_image)),input_box)
            vector,input_box=vectors_by_mode[cache_key]
            if vector is None:row['scores'][rank]={'status':'unavailable','similarity':None};continue
            similarities=centroids@vector;best=int(np.argmax(similarities));score=float(similarities[best]);accepted=score>=frozen['threshold']
            row[rank]=labels[best] if accepted else None;row['scores'][rank]={'status':'accepted' if accepted else 'abstained','similarity':score,'threshold':frozen['threshold'],
                                                                              'crop_framing':framing,'input_bbox_xyxy':list(input_box)}
            if mode=='masked' or framing=='mask_bounds_8':row['scores'][rank]['mask_sha256']=digest(mask_path)
        predictions.append(row)
    result={'format':'diatom-frozen-field-predictions-v1','protocol_sha256':digest(a.protocol),'field_id':a.field_id,'sample_id':field['sample_id'],
            'bundle_sha256':digest(bundle_file),'bundle_id':bundle['bundle_id'],'field_image_sha256':image_hash,'candidate_policy':protocol['candidate_policy'],'source_manifest_sha256':proposal_hashes,
            'predictions':predictions,'warning':'Unmatched predictions only. Frozen settings and sample independence are declarations; this does not measure accuracy or validate biological identities.'}
    a.output.parent.mkdir(parents=True,exist_ok=True)
    with a.output.open('x') as f:json.dump(result,f,indent=2);f.write('\n')
    print(f'Scored {len(predictions)} proposals under the frozen policy; no references matched and no accuracy computed.')


if __name__=='__main__':main()
