"""Collect independent field references and declared expert visual matches."""
import argparse
import json
from pathlib import Path
from ingest_review import digest,inside


def main():
    p=argparse.ArgumentParser(description=__doc__);p.add_argument('--protocol',type=Path,required=True)
    p.add_argument('--reference',type=Path,action='append',required=True);p.add_argument('--predictions',type=Path,action='append',required=True)
    p.add_argument('--matches',type=Path,action='append',required=True);p.add_argument('--additional-development-sample',action='append',default=[])
    p.add_argument('--matching-page',type=Path,action='append',required=True,help='Generated matching-page directory; repeat for every field')
    p.add_argument('--output',type=Path,required=True);a=p.parse_args();protocol=json.loads(a.protocol.read_text());protocol_hash=digest(a.protocol)
    if protocol.get('format')!='diatom-frozen-field-protocol-v1':raise ValueError('Invalid frozen protocol')
    locked=protocol.get('fields');dev=protocol.get('development_sample_ids')
    if not isinstance(locked,list) or not locked or not isinstance(dev,list):raise ValueError('Invalid frozen field or sample list')
    def keyed(paths,key,fmt):
        found={}
        for path in paths:
            obj=json.loads(path.read_text());ident=obj.get(key)
            if obj.get('format')!=fmt or not isinstance(ident,str) or not ident or ident in found:raise ValueError(f'Invalid or duplicate {fmt}')
            found[ident]=(obj,path)
        return found
    refs=keyed(a.reference,'field_id','diatom-independent-field-reference-v1');preds=keyed(a.predictions,'field_id','diatom-frozen-field-predictions-v1')
    matches={}
    for path in a.matches:
        obj=json.loads(path.read_text());display=obj.get('display');ident=display.get('field_id') if isinstance(display,dict) else None
        if obj.get('format')!='diatom-field-matches-v1' or not isinstance(ident,str) or not ident or ident in matches:raise ValueError('Invalid or duplicate match decisions')
        matches[ident]=(obj,path)
    pages={}
    for directory in a.matching_page:
        page=directory/'index.html';source=page.read_text();marker='const payload='
        if source.count(marker)!=1:raise ValueError('Matching page has no unique display payload')
        try:display,_=json.JSONDecoder().raw_decode(source.split(marker,1)[1])
        except (json.JSONDecodeError,ValueError) as exc:raise ValueError('Invalid matching page display payload') from exc
        ident=display.get('field_id') if isinstance(display,dict) else None
        if not isinstance(ident,str) or not ident or ident in pages:raise ValueError('Invalid or duplicate matching page')
        pages[ident]=(display,directory,page)
    identities=[f.get('id') for f in locked if isinstance(f,dict)]
    if len(identities)!=len(locked) or len(set(identities))!=len(identities) or set(identities)!=set(refs) or set(identities)!=set(preds) or set(identities)!=set(matches) or set(identities)!=set(pages):raise ValueError('All frozen fields need exactly one reference, prediction, matching page and match file')
    fields=[];reviewers=set();provenance={}
    for field in locked:
        ident=field['id'];ref,ref_path=refs[ident];pred,pred_path=preds[ident];match,match_path=matches[ident];display=match['display'];sample=field.get('sample_id');page_display,page_dir,page_path=pages[ident]
        if (ref.get('protocol_sha256')!=protocol_hash or pred.get('protocol_sha256')!=protocol_hash or display.get('protocol_sha256')!=protocol_hash
            or ref.get('sample_id')!=sample or pred.get('sample_id')!=sample or display.get('sample_id')!=sample
            or display.get('reference_sha256')!=digest(ref_path) or display.get('predictions_sha256')!=digest(pred_path)
            or ref.get('field_image_sha256')!=pred.get('field_image_sha256') or ref.get('exhaustive') is not True
            or ref.get('reference_status')!='expert_adjudicated' or ref.get('reviewer_role')!='expert'
            or not isinstance(ref.get('reviewer_id'),str) or not ref['reviewer_id'].strip()
            or match.get('reviewer_role')!='expert' or not isinstance(match.get('reviewer_id'),str) or not match['reviewer_id'].strip()
            or not isinstance(ref.get('references'),list) or not isinstance(pred.get('predictions'),list) or not isinstance(match.get('matches'),list)):
            raise ValueError(f'Invalid evidence or expert declarations for {ident}')
        if display!=page_display or not isinstance(display.get('asset_sha256'),dict) or not display['asset_sha256']:
            raise ValueError('Matching page display does not match the exported decisions')
        if display.get('mask_rule_id')!=protocol.get('mask_rule_id'):raise ValueError('Matching page mask rule differs from the frozen protocol')
        for name,expected_hash in display['asset_sha256'].items():
            if not isinstance(name,str) or not isinstance(expected_hash,str) or digest(inside(page_dir,name))!=expected_hash:
                raise ValueError('Matching page image hash mismatch')
        pred_ids=[x.get('id') for x in pred['predictions']];ref_ids=[x.get('id') for x in ref['references']];matched=[x.get('prediction_id') for x in match['matches']]
        if (any(not isinstance(x,str) or not x for x in pred_ids+ref_ids+matched) or len(set(pred_ids))!=len(pred_ids)
            or len(set(ref_ids))!=len(ref_ids) or len(set(matched))!=len(matched) or set(pred_ids)!=set(matched)
            or display.get('prediction_ids')!=pred_ids or [x.get('id') for x in display.get('references',[])]!=ref_ids):raise ValueError('Reference or match IDs do not agree with the displayed evidence')
        if display.get('proposal_plane_by_prediction') is not None:
            expected_planes={item['id']:item.get('plane_z',display.get('display_plane_z')) for item in pred['predictions']}
            if (display['proposal_plane_by_prediction']!=expected_planes
                or display.get('references')!=[{'id':item['id'],'z':item.get('z')} for item in ref['references']]):
                raise ValueError('Displayed focal planes do not match the reference and predictions')
        statuses={item['id']:item.get('mask_status','unknown') for item in pred['predictions']}
        displayed_status=display.get('mask_status_by_prediction',{})
        if displayed_status and (not isinstance(displayed_status,dict) or set(displayed_status)!=set(pred_ids)
            or any(status!='unknown' and displayed_status[ident]!=status for ident,status in statuses.items())):
            raise ValueError('Displayed mask status differs from frozen predictions')
        used=set()
        for choice in match['matches']:
            target=choice.get('reference_id');assessment=choice.get('mask_assessment','not_reviewed');status=statuses[choice['prediction_id']]
            if assessment not in {'not_reviewed','acceptable','unacceptable','merged','unsure','unavailable','not_applicable'}:raise ValueError('Invalid mask assessment')
            extras=choice.get('merged_reference_ids',[])
            if (not isinstance(extras,list) or any(not isinstance(x,str) or x not in ref_ids for x in extras)
                or len(set(extras))!=len(extras) or (extras and (assessment!='merged' or target is None or target in extras))):
                raise ValueError('Invalid additional references for merged mask')
            if target is None:
                if choice.get('unmatched_type') not in ('duplicate','other','unknown'):raise ValueError('Unmatched proposal requires a type')
                if assessment not in {'not_reviewed','not_applicable'}:raise ValueError('Unmatched proposals cannot have a specimen-specific mask assessment')
            else:
                if target not in ref_ids or target in used or choice.get('unmatched_type') is not None:raise ValueError('Invalid or repeated reference match')
                if assessment=='not_applicable' or (assessment=='unavailable' and status not in {'empty','missing'}) or (assessment in {'acceptable','unacceptable','merged','unsure'} and (status!='nonempty' or not protocol.get('mask_rule_id'))):
                    raise ValueError('Mask assessment conflicts with the frozen rule or mask status')
                used.add(target)
        reviewers.add(match['reviewer_id'].strip());fields.append({'id':ident,'sample_id':sample,'exhaustive':True,'predictions_sha256':digest(pred_path),
                         'references':ref['references'],'matches':match['matches']})
        provenance[ident]={'reference_sha256':digest(ref_path),'matches_sha256':digest(match_path),'reference_reviewer_id':ref['reviewer_id'].strip(),
                           'matching_reviewer_id':match['reviewer_id'].strip(),'matching_page_sha256':digest(page_path),
                           'display_asset_sha256':display.get('asset_sha256')}
    all_dev=dev+a.additional_development_sample
    if any(not isinstance(x,str) or not x or x!=x.strip() for x in all_dev):raise ValueError('Invalid development sample ID')
    result={'format':'diatom-expert-field-reference-v1','protocol_sha256':protocol_hash,'reference_status':'expert_adjudicated','matching_status':'expert_adjudicated',
            'reviewer_role':'expert','reviewer_id':', '.join(sorted(reviewers)),'matching_rule_id':protocol['matching_rule_id'],'taxonomy_version':protocol['taxonomy_version'],
            'development_sample_ids':sorted(set(all_dev)),'fields':fields,'field_provenance':provenance,
            'warning':'Expertise, independence, exhaustive reference status and actual image viewing are declarations, not verified facts.'}
    a.output.parent.mkdir(parents=True,exist_ok=True)
    with a.output.open('x') as out:json.dump(result,out,indent=2);out.write('\n')
    print(f'Collected declared expert references and matches for {len(fields)} fields; declarations are not verified.')


if __name__=='__main__':main()
