"""Freeze a validation-selected centroid threshold and model provenance."""
import argparse
import json
import math
from pathlib import Path

from ingest_review import digest


def main():
    p=argparse.ArgumentParser(description=__doc__);p.add_argument('--model',type=Path,required=True)
    p.add_argument('--validation-report',type=Path,required=True);p.add_argument('--protocol-id',required=True)
    p.add_argument('--allow-no-crop-test-rows',action='store_true',help='Freeze for a separately declared field test when the dataset has no labeled test crops')
    p.add_argument('--threshold',type=float,required=True);p.add_argument('--output',type=Path,required=True);a=p.parse_args()
    if not a.protocol_id or a.protocol_id!=a.protocol_id.strip():p.error('Protocol ID must be nonempty')
    if not math.isfinite(a.threshold) or not -1<=a.threshold<=1:p.error('Threshold must be finite and between -1 and 1')
    model_file=a.model/'model.json';model=json.loads(model_file.read_text());report=json.loads(a.validation_report.read_text())
    rank=model.get('label_rank','species')
    test_rows=model.get('held_out_test_rows')
    if (model.get('format')!='diatom-centroid-classifier-v1' or rank not in {'genus','species'}
        or model.get('test_status')!='test images not opened or scored' or type(test_rows) is not int or test_rows<0
        or (test_rows==0 and not a.allow_no_crop_test_rows)):raise ValueError('Model needs declared untouched test rows, or explicit field-only opt-in')
    if digest(a.model/'centroids.npz')!=model['centroids_sha256']:raise ValueError('Centroid hash mismatch')
    if (report.get('format')!='diatom-centroid-threshold-report-v1' or report.get('model_sha256')!=digest(model_file)
        or report.get('validation_samples')!=model['validation_samples']):raise ValueError('Validation report does not match model')
    options=report.get(rank,{}).get('results',[])
    selected=[r for r in options if r.get('threshold')==a.threshold]
    if len(selected)!=1 or selected[0].get('eligible',0)<1:raise ValueError('Threshold is not in a nonempty validation report for this rank')
    result={'format':'diatom-centroid-frozen-protocol-v1','protocol_id':a.protocol_id,'rank':rank,'threshold':a.threshold,
            'threshold_rule':'accept if cosine similarity >= threshold','threshold_source':'declared_validation_report',
            'model_sha256':digest(model_file),'centroids_sha256':model['centroids_sha256'],'dataset_sha256':model['dataset_sha256'],
            'encoder_sha256':model['encoder_sha256'],'validation_report_sha256':digest(a.validation_report),
            'field_only_without_labeled_test_crops':test_rows==0,
            'warning':'Frozen file does not prove independent sampling, expert adjudication, prior nonexposure, or a scientifically approved protocol.'}
    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'Frozen {rank} threshold {a.threshold}; no test images were opened.')


if __name__=='__main__':main()
