"""Assemble an evaluation manifest from frozen predictions and declared expert matches."""
import argparse
import json
from pathlib import Path

from evaluate_instances import evaluate
from ingest_review import digest


def main():
    p=argparse.ArgumentParser(description=__doc__)
    p.add_argument('--protocol',type=Path,required=True)
    p.add_argument('--predictions',type=Path,action='append',required=True,help='Frozen field predictions; repeat for each declared field')
    p.add_argument('--expert-reference',type=Path,required=True,help='References and explicit prediction matches; never inferred')
    p.add_argument('--taxonomy-map',type=Path,help='Exact predeclared taxonomy map, if frozen in the protocol')
    p.add_argument('--output',type=Path,required=True);a=p.parse_args()
    protocol=json.loads(a.protocol.read_text());reference=json.loads(a.expert_reference.read_text());protocol_hash=digest(a.protocol)
    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:raise ValueError('Invalid frozen field protocol')
    taxonomy_hash=protocol.get('taxonomy_map_sha256');taxonomy=None
    if bool(taxonomy_hash)!=bool(a.taxonomy_map):raise ValueError('Provide exactly the taxonomy map specified by the frozen protocol')
    if a.taxonomy_map:
        taxonomy_data=json.loads(a.taxonomy_map.read_text());taxonomy=taxonomy_data.get('species_to_genus')
        if (digest(a.taxonomy_map)!=taxonomy_hash or taxonomy_data.get('format')!='diatom-taxonomy-map-v1'
            or taxonomy_data.get('version')!=protocol.get('taxonomy_version') or not isinstance(taxonomy,dict) or not taxonomy
            or any(not isinstance(k,str) or not k or k!=k.strip() or not isinstance(v,str) or not v or v!=v.strip() for k,v in taxonomy.items())):
            raise ValueError('Taxonomy map does not match the frozen protocol')
    for key in ('protocol_id','matching_rule_id','taxonomy_version'):
        value=protocol.get(key)
        if not isinstance(value,str) or not value or value!=value.strip():raise ValueError(f'Missing frozen {key}')
    if (reference.get('format')!='diatom-expert-field-reference-v1' or reference.get('protocol_sha256')!=protocol_hash
        or reference.get('reference_status')!='expert_adjudicated' or reference.get('matching_status')!='expert_adjudicated'
        or reference.get('reviewer_role')!='expert' or not isinstance(reference.get('reviewer_id'),str) or not reference['reviewer_id'].strip()
        or reference.get('matching_rule_id')!=protocol['matching_rule_id'] or reference.get('taxonomy_version')!=protocol['taxonomy_version']):
        raise ValueError('Expert reference declarations or frozen protocol do not match')
    frozen_fields=protocol.get('fields');reference_fields=reference.get('fields');development=reference.get('development_sample_ids')
    if not isinstance(frozen_fields,list) or not frozen_fields or not isinstance(reference_fields,list) or not isinstance(development,list):raise ValueError('Invalid field lists')
    frozen_development=protocol.get('development_sample_ids')
    if (not isinstance(frozen_development,list) or any(not isinstance(x,str) or not x for x in frozen_development+development)
        or not set(frozen_development).issubset(development)):
        raise ValueError('Expert reference must include every frozen model development sample ID')
    def field_map(fields):
        result={}
        for field in fields:
            if not isinstance(field,dict) or not isinstance(field.get('id'),str) or not field['id'] or field['id'] in result:raise ValueError('Invalid or duplicate field ID')
            result[field['id']]=field
        return result
    locked=field_map(frozen_fields);refs=field_map(reference_fields);preds={};hashes={}
    if set(locked)!=set(refs):raise ValueError('Expert reference fields do not match frozen field list')
    for path in a.predictions:
        data=json.loads(path.read_text());ident=data.get('field_id')
        if (data.get('format')!='diatom-frozen-field-predictions-v1' or data.get('protocol_sha256')!=protocol_hash
            or data.get('candidate_policy')!=protocol['candidate_policy'] or not isinstance(ident,str) or ident not in locked or ident in preds
            or data.get('sample_id')!=locked[ident].get('sample_id') or not isinstance(data.get('predictions'),list)):
            raise ValueError('Invalid, duplicate or mismatched field predictions')
        preds[ident]=data;hashes[ident]=digest(path)
    if set(preds)!=set(locked):raise ValueError('Predictions are required for every frozen field')
    fields=[]
    for ident,frozen in locked.items():
        ref=refs[ident];source=preds[ident]
        if (ref.get('sample_id')!=frozen.get('sample_id') or ref.get('exhaustive') is not True
            or ref.get('predictions_sha256')!=hashes[ident] or not isinstance(ref.get('references'),list) or not isinstance(ref.get('matches'),list)):
            raise ValueError(f'Invalid reference or prediction provenance for {ident}')
        if taxonomy is not None:
            for r in ref['references']:
                if not isinstance(r,dict):raise ValueError('Invalid reference')
                species=r.get('species');genus=r.get('genus')
                if r.get('species_eligible') is True:
                    if not isinstance(species,str) or species not in taxonomy:raise ValueError(f'Eligible reference species absent from frozen taxonomy: {species}')
                    if genus is not None and genus!=taxonomy[species]:raise ValueError(f'Reference genus conflicts with frozen taxonomy: {species}')
        matches={}
        reference_by_id={r['id']:r for r in ref['references'] if isinstance(r,dict) and isinstance(r.get('id'),str)}
        reference_ids=set(reference_by_id)
        for match in ref['matches']:
            if not isinstance(match,dict) or not isinstance(match.get('prediction_id'),str) or match['prediction_id'] in matches:raise ValueError('Invalid or repeated prediction match')
            matches[match['prediction_id']]=match
        predictions=[];seen=set()
        for prediction in source['predictions']:
            if not isinstance(prediction,dict):raise ValueError('Invalid frozen prediction')
            name=prediction.get('id')
            if not isinstance(name,str) or not name or name in seen or name not in matches:raise ValueError('Each prediction requires exactly one expert match')
            seen.add(name);match=matches[name];reference_id=match.get('reference_id')
            mask_status=prediction.get('mask_status','unknown')
            if mask_status not in {'nonempty','empty','missing','unknown'}:raise ValueError('Invalid prediction mask status')
            assessment=match.get('mask_assessment','not_reviewed')
            if assessment not in {'not_reviewed','acceptable','unacceptable','merged','unsure','unavailable','not_applicable'}:raise ValueError('Invalid mask assessment')
            if ((reference_id is None and assessment not in {'not_reviewed','not_applicable'})
                or (reference_id is not None and assessment=='not_applicable')
                or (assessment=='unavailable' and mask_status not in {'empty','missing'})
                or (assessment in {'acceptable','unacceptable','merged','unsure'} and (mask_status!='nonempty' or not protocol.get('mask_rule_id')))):
                raise ValueError('Mask assessment conflicts with the match, mask status or frozen rule')
            extras=match.get('merged_reference_ids',[])
            if (not isinstance(extras,list) or any(not isinstance(x,str) or x not in reference_ids for x in extras)
                or len(set(extras))!=len(extras) or (extras and (assessment!='merged' or reference_id is None or reference_id in extras))):
                raise ValueError('Invalid additional references for merged mask')
            item={'id':name,'reference_id':reference_id,'genus':prediction.get('genus'),'species':prediction.get('species'),
                  'mask_status':mask_status,'mask_assessment':assessment,'merged_reference_ids':extras}
            reference_z=reference_by_id.get(reference_id,{}).get('z');proposal_z=prediction.get('plane_z')
            item['focal_plane_relation']=('not_applicable' if reference_id is None else
                ('same' if reference_z==proposal_z else 'different') if type(reference_z) is int and type(proposal_z) is int else 'unknown')
            genus,species=item['genus'],item['species']
            if taxonomy is None:item['taxonomy_status']='not_checked'
            elif genus is None or species is None:item['taxonomy_status']='not_applicable'
            elif not isinstance(species,str) or species not in taxonomy:item['taxonomy_status']='unmapped'
            else:item['taxonomy_status']='consistent' if genus==taxonomy[species] else 'conflicting'
            if reference_id is None:item['unmatched_type']=match.get('unmatched_type')
            elif match.get('unmatched_type') is not None:raise ValueError('Matched prediction cannot have an unmatched type')
            predictions.append(item)
        if seen!=set(matches):raise ValueError('Expert matches contain unknown prediction IDs')
        fields.append({'field_id':ident,'sample_id':frozen['sample_id'],'exhaustive':True,
                       'references':ref['references'],'predictions':predictions})
    result={'format':'diatom-instance-evaluation-v1','split':'held_out_test','protocol_id':protocol['protocol_id'],
            'matching_rule_id':protocol['matching_rule_id'],'mask_rule_id':protocol.get('mask_rule_id'),'taxonomy_version':protocol['taxonomy_version'],
            'field_overlap_handling_id':protocol.get('overlap_handling_id'),'overlapping_field_pairs':protocol.get('overlapping_field_pairs'),
            'reference_status':reference['reference_status'],'matching_status':reference['matching_status'],
            'development_sample_ids':development,'fields':fields,
            'provenance':{'field_protocol_sha256':protocol_hash,'expert_reference_sha256':digest(a.expert_reference),
                          'prediction_sha256_by_field':hashes,'taxonomy_map_sha256':taxonomy_hash,'declared_reviewer_id':reference['reviewer_id'].strip()},
            'warning':'Expertise, exhaustive annotation, matching, sample independence and test nonexposure are declarations, not verified facts.'}
    evaluate(result)  # Reject inconsistent matches and invalid labels before writing.
    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'Assembled {len(fields)} declared expert-matched fields; no accuracy computed.')


if __name__=='__main__':main()
