"""Apply declared expert decisions to a copy of a reviewed specimen package."""
import argparse
import copy
import json
import shutil
from pathlib import Path

from ingest_review import digest,inside


def main():
    p=argparse.ArgumentParser(description=__doc__);p.add_argument('--package',type=Path,required=True)
    p.add_argument('--decisions',type=Path,required=True);p.add_argument('--output',type=Path,required=True)
    p.add_argument('--display-bundle',type=Path,help='Field bundle used for focal-plane review, when recorded');a=p.parse_args()
    manifest=a.package/'specimens.json';source=json.loads(manifest.read_text());decisions=json.loads(a.decisions.read_text())
    if source.get('format')!='diatom-reviewed-specimens-v1' or source.get('adjudicated') is not False:raise ValueError('Expected original unadjudicated specimen package')
    if decisions.get('format')!='diatom-specimen-adjudication-v1' or decisions.get('source_package_sha256')!=digest(manifest):raise ValueError('Adjudication does not match source package')
    display=decisions.get('display_provenance')
    if display is not None:
        if not isinstance(display,dict) or not a.display_bundle:raise ValueError('Matching display bundle is required for focal-plane adjudication')
        bundle=json.loads((a.display_bundle/'bundle.json').read_text());focus_file=a.display_bundle/'focus-planes.json';focus=json.loads(focus_file.read_text())
        if (display.get('bundle_id')!=source.get('bundle_id') or bundle.get('bundle_id')!=source.get('bundle_id')
            or bundle.get('slide')!=source.get('slide') or bundle.get('origin_xy')!=source.get('origin_xy')
            or focus.get('bundle_id')!=bundle['bundle_id'] or digest(focus_file)!=display.get('focus_manifest_sha256')
            or display.get('planes')!=[{'z':x['z'],'sha256':x['sha256']} for x in focus['planes']]):raise ValueError('Display bundle or focal-plane provenance mismatch')
        for plane in focus['planes']:
            if digest(inside(a.display_bundle,plane['image']))!=plane['sha256']:raise ValueError('Display focal-plane image hash mismatch')
    reviewer=decisions.get('reviewer_id');protocol=decisions.get('protocol_id')
    if decisions.get('reviewer_role')!='expert' or not isinstance(reviewer,str) or not reviewer.strip() or not isinstance(protocol,str) or not protocol.strip():
        raise ValueError('An expert reviewer ID and protocol ID must be explicitly declared')
    records=source.get('specimens');choices=decisions.get('decisions')
    if not isinstance(records,list) or not isinstance(choices,list):raise ValueError('Invalid specimen or decision list')
    byid={x['id']:x for x in records};selected={x['specimen_id']:x for x in choices}
    if len(byid)!=len(records) or len(selected)!=len(choices) or set(selected)-set(byid):raise ValueError('Duplicate or unknown specimen ID')
    result=copy.deepcopy(source);output_byid={x['id']:x for x in result['specimens']};counts={'confirmed':0,'rejected':0,'unsure':0,'not_reviewed':len(records)-len(choices)}
    relationships=result.get('candidate_relationships',[]);pair_choices=decisions.get('pair_decisions',[])
    if not isinstance(relationships,list) or not isinstance(pair_choices,list):raise ValueError('Invalid pair decisions')
    pairs={}
    for relation in relationships:
        if not isinstance(relation,dict):raise ValueError('Invalid source candidate relationship')
        left,right=relation.get('a'),relation.get('b')
        if not isinstance(left,str) or not isinstance(right,str) or left>=right or (left,right) in pairs:raise ValueError('Invalid source candidate relationship')
        pairs[(left,right)]=relation
    seen_pairs=set()
    for choice in pair_choices:
        if not isinstance(choice,dict):raise ValueError('Invalid pair decision')
        left,right,assessment,note=choice.get('a'),choice.get('b'),choice.get('relation'),choice.get('note')
        if (not isinstance(left,str) or not isinstance(right,str) or (left,right) not in pairs or (left,right) in seen_pairs
            or not isinstance(assessment,str) or assessment not in {'same','different','unsure'} or not isinstance(note,str)):
            raise ValueError('Invalid, duplicate or unknown pair decision')
        seen_pairs.add((left,right))
        pairs[(left,right)]['expert_assessment']={'relation':assessment,'note':note,'reviewer_id':reviewer.strip(),
            'reviewer_role':'expert','protocol_id':protocol.strip(),'decisions_sha256':digest(a.decisions)}
    for ident,choice in selected.items():
        verdict=choice.get('verdict');rank=choice.get('taxon_rank');label=choice.get('taxon_text');certainty=choice.get('certainty');note=choice.get('note')
        if verdict not in {'confirmed','rejected','unsure'} or rank not in {'unknown','genus','species','other'} or not isinstance(label,str) or label!=label.strip() or certainty not in {'unknown','tentative','confident','unresolved'} or not isinstance(note,str):raise ValueError('Invalid adjudication decision')
        if (rank=='unknown')!= (not label):raise ValueError('Taxon text and rank must either both be specified or both be unknown')
        if verdict!='confirmed' and (rank!='unknown' or certainty not in {'unknown','unresolved'}):raise ValueError('Rejected or unsure specimens cannot receive a confirmed taxon')
        if certainty=='unresolved' and rank!='unknown':raise ValueError('Unresolved identification cannot have a confirmed taxon')
        specimen=output_byid[ident];specimen['original_annotation']={k:specimen.get(k) for k in ('decision','taxon_text','taxon_rank','identification_certainty','note','adjudicated','annotation_status')}
        specimen['adjudication']={'verdict':verdict,'reviewer_id':reviewer.strip(),'reviewer_role':'expert','protocol_id':protocol.strip(),
                                  'decisions_sha256':digest(a.decisions),'note':note}
        specimen['decision']={'confirmed':'countable','rejected':'reject','unsure':'unsure'}[verdict]
        specimen['taxon_text']=label;specimen['taxon_rank']=rank;specimen['identification_certainty']=certainty
        specimen['adjudicated']=verdict in {'confirmed','rejected'};specimen['annotation_status']='expert_adjudicated' if specimen['adjudicated'] else 'expert_unsure'
        counts[verdict]+=1
    result['adjudicated']=True
    result['adjudication']={'reviewer_id':reviewer.strip(),'reviewer_role':'expert','protocol_id':protocol.strip(),
                            'source_package_sha256':digest(manifest),'decisions_sha256':digest(a.decisions),
                            'display_provenance':display,'counts':counts}
    result['warning']='Expert status and adjudication are declarations; masks, duplicate identities, sample independence and field exhaustiveness remain separate questions.'
    if a.output.exists() and any(a.output.iterdir()):raise FileExistsError('Output directory must be empty')
    for specimen in records:
        crop=specimen.get('crop')
        if not crop:continue
        for key,hash_key in [('image','image_sha256'),('mask','mask_sha256')]:
            name=crop.get(key)
            if name is None:continue
            path=inside(a.package,name)
            if digest(path)!=crop.get(hash_key):raise ValueError('Specimen asset hash mismatch')
    a.output.mkdir(parents=True,exist_ok=True)
    for specimen in records:
        crop=specimen.get('crop')
        if not crop:continue
        for key in ('image','mask'):
            name=crop.get(key)
            if name is not None:
                target=a.output/name;target.parent.mkdir(parents=True,exist_ok=True);shutil.copyfile(inside(a.package,name),target)
    (a.output/'specimens.json').write_text(json.dumps(result,indent=2)+'\n')
    print(f'Applied declared expert decisions: {counts}; original package remains unchanged.')


if __name__=='__main__':main()
