"""Compute instance-level metrics from explicitly adjudicated evaluation records.

This does not establish that the submitted references, matching, taxonomy,
sample split, or reported review status are scientifically valid.
"""
import argparse
import hashlib
import json
import math
import random
from collections import Counter,defaultdict
from pathlib import Path


def text(value,name,allow_empty=False):
    if not isinstance(value,str) or value!=value.strip() or (not allow_empty and not value):raise ValueError(f'Invalid {name}')
    return value


def rate(n,d):return n/d if d else None


def cluster_bootstrap(per_sample,replicates=2000,seed=0):
    """Percentile intervals for pooled correct/eligible, resampling sample IDs."""
    if type(replicates) is not int or not 100<=replicates<=100000:raise ValueError('Bootstrap replicates must be 100–100000')
    if type(seed) is not int:raise ValueError('Bootstrap seed must be an integer')
    samples=sorted(per_sample);count=len(samples)
    if count<2:raise ValueError('At least two distinct test samples are required for bootstrap')
    rng=random.Random(seed);draws={'genus':[],'species':[]};zero={'genus':0,'species':0}
    for _ in range(replicates):
        chosen=[per_sample[rng.choice(samples)] for _ in samples]
        for rank in draws:
            numerator=sum(s[rank]['correct'] for s in chosen);denominator=sum(s[rank]['eligible'] for s in chosen)
            if denominator:draws[rank].append(numerator/denominator)
            else:zero[rank]+=1
    def quantile(values,q):
        if not values:return None
        values.sort();i=(len(values)-1)*q;lo=math.floor(i);hi=math.ceil(i)
        return values[lo]+(values[hi]-values[lo])*(i-lo)
    return {'method':'sample-cluster percentile bootstrap of pooled correct/eligible',
            'confidence_level':.95,'seed':seed,'replicates':replicates,'sample_count':count,
            'ranks':{rank:{'lower':quantile(v,.025),'upper':quantile(v,.975),
                           'valid_replicates':len(v),'zero_denominator_replicates':zero[rank]} for rank,v in draws.items()},
            'warning':'Sample IDs must represent independent biological samples. Percentile intervals can be unstable with few samples or rare errors and can be spuriously narrow when all observed outcomes agree; they do not establish target achievement.'}


def evaluate(data, *, development=False, provisional=False):
    if provisional and not development:raise ValueError('Provisional evaluation is allowed only for development')
    expected='development' if development else 'held_out_test'
    if data.get('format')!='diatom-instance-evaluation-v1' or data.get('split')!=expected:raise ValueError(f'Expected a {expected} manifest')
    text(data.get('protocol_id'),'protocol ID');text(data.get('matching_rule_id'),'matching rule ID');text(data.get('taxonomy_version'),'taxonomy version')
    if data.get('mask_rule_id') is not None:text(data['mask_rule_id'],'mask rule ID')
    review_status='provisional' if provisional else 'expert_adjudicated'
    if data.get('reference_status')!=review_status or data.get('matching_status')!=review_status:
        raise ValueError(f'{review_status} references and matches must be declared')
    samples=data.get('development_sample_ids');fields=data.get('fields')
    if not isinstance(samples,list) or len(set(samples))!=len(samples) or any(not isinstance(x,str) or not x or x!=x.strip() for x in samples):raise ValueError('Invalid development sample IDs')
    if not isinstance(fields,list) or not fields:raise ValueError('No test fields')
    all_rows=[];all_groups=[];all_unmatched=[];all_predictions=[];field_results=[];field_ids=set();test_samples=set()
    for f in fields:
        field_id=text(f.get('field_id'),'field ID');sample=text(f.get('sample_id'),'sample ID')
        if field_id in field_ids or sample in samples:raise ValueError('Duplicate field or sample leakage')
        field_ids.add(field_id);test_samples.add(sample)
        if f.get('exhaustive') is not True:raise ValueError('Each field must be declared exhaustively annotated')
        refs=f.get('references');preds=f.get('predictions')
        if not isinstance(refs,list) or not isinstance(preds,list):raise ValueError('Invalid reference or prediction list')
        byid={};groups=defaultdict(list)
        for ref in refs:
            ident=text(ref.get('id'),'reference ID')
            if ident in byid:raise ValueError('Duplicate reference ID')
            byid[ident]=ref
            if ref.get('partial') not in ('yes','no','unknown'):raise ValueError('Invalid partial flag')
            group=text(ref.get('overlap_group',''),'overlap group',True)
            if group:groups[group].append(ident)
            for rank in ('genus','species'):
                eligible=ref.get(rank+'_eligible')
                if type(eligible) is not bool:raise ValueError('Eligibility must be explicit')
                value=ref.get(rank)
                if eligible:text(value,rank)
                elif value is not None:text(value,rank)
        if any(len(group)<2 for group in groups.values()):raise ValueError('Overlap group must contain at least two reference specimens in the field')
        pred_ids=set();assigned={};unmatched=Counter()
        for pred in preds:
            ident=text(pred.get('id'),'prediction ID')
            if ident in pred_ids:raise ValueError('Duplicate prediction ID')
            pred_ids.add(ident)
            for rank in ('genus','species'):
                if pred.get(rank) is not None:text(pred[rank],f'predicted {rank}')
            if pred.get('mask_status','unknown') not in {'nonempty','empty','missing','unknown'}:raise ValueError('Invalid prediction mask status')
            taxonomy_status=pred.get('taxonomy_status','not_checked')
            if (taxonomy_status not in {'consistent','conflicting','unmapped','not_applicable','not_checked'}
                or (taxonomy_status in {'consistent','conflicting','unmapped'} and (pred.get('genus') is None or pred.get('species') is None))
                or (taxonomy_status=='not_applicable' and pred.get('genus') is not None and pred.get('species') is not None)):
                raise ValueError('Invalid prediction taxonomy status')
            all_predictions.append({'sample_id':sample,'prediction':pred})
            match=pred.get('reference_id')
            plane_relation=pred.get('focal_plane_relation','unknown')
            if (plane_relation not in {'same','different','unknown','not_applicable'}
                or (match is not None and plane_relation=='not_applicable')
                or (match is None and plane_relation in {'same','different'})):
                raise ValueError('Invalid focal-plane relationship for this match')
            assessment=pred.get('mask_assessment','not_reviewed');mask_status=pred.get('mask_status','unknown')
            if (assessment not in {'not_reviewed','acceptable','unacceptable','merged','unsure','unavailable','not_applicable'}
                or (match is None and assessment not in {'not_reviewed','not_applicable'})
                or (match 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 data.get('mask_rule_id')))):
                raise ValueError('Invalid mask assessment for this match or protocol')
            extras=pred.get('merged_reference_ids',[])
            if (not isinstance(extras,list) or any(not isinstance(x,str) or x not in byid for x in extras)
                or len(set(extras))!=len(extras) or (extras and (assessment!='merged' or match is None or match in extras))):
                raise ValueError('Invalid additional references for merged mask')
            if match is None:
                kind=pred.get('unmatched_type')
                if kind not in ('duplicate','other','unknown'):raise ValueError('Unmatched prediction needs a type')
                unmatched[kind]+=1
                all_unmatched.append({'sample_id':sample,'field_id':field_id,'type':kind,'prediction':pred})
            else:
                if match not in byid or match in assigned:raise ValueError('Unknown reference or multiple matches for one reference')
                if pred.get('unmatched_type') is not None:raise ValueError('Matched prediction cannot have an unmatched type')
                assigned[match]=pred
        rows=[{'sample_id':sample,'field_id':field_id,'reference':ref,'prediction':assigned.get(ident)} for ident,ref in byid.items()]
        all_rows.extend(rows)
        for group_id,members in groups.items():
            all_groups.append({'sample_id':sample,'field_id':field_id,'group_id':group_id,
                               'members':[{'reference':byid[x],'prediction':assigned.get(x)} for x in members]})
        field_results.append({'field_id':field_id,'sample_id':sample,'reference_instances':len(refs),'matched_instances':len(assigned),
                              'missed_instances':len(refs)-len(assigned),'unmatched_predictions':dict(unmatched),
                              'additional_references_in_merged_masks':len({x for p in preds for x in p.get('merged_reference_ids',[])}),
                              'unmatched_references_in_merged_masks':len({x for p in preds for x in p.get('merged_reference_ids',[]) if x not in assigned}),
                              'overlap_groups':len(groups),'completely_recovered_overlap_groups':sum(all(x in assigned for x in members) for members in groups.values())})

    field_overlap_rule=data.get('field_overlap_handling_id');field_overlaps=data.get('overlapping_field_pairs')
    if field_overlap_rule is not None:text(field_overlap_rule,'field overlap rule ID')
    if field_overlaps is not None:
        if not isinstance(field_overlaps,list):raise ValueError('Invalid field overlap declarations')
        seen_overlaps=set()
        for pair in field_overlaps:
            if (not isinstance(pair,list) or len(pair)!=2 or any(not isinstance(x,str) or x not in field_ids for x in pair)
                or pair[0]==pair[1] or tuple(sorted(pair)) in seen_overlaps):raise ValueError('Invalid or duplicate field overlap')
            seen_overlaps.add(tuple(sorted(pair)))
        if field_overlaps and not field_overlap_rule:raise ValueError('Overlapping test fields require a declared handling rule')

    def summarize(rows):
        result={'instances':len(rows),'detected':sum(x['prediction'] is not None for x in rows)}
        detected=[x for x in rows if x['prediction'] is not None]
        result['matched_mask_status']={status:sum(x['prediction'].get('mask_status','unknown')==status for x in detected)
                                       for status in ('nonempty','empty','missing','unknown')}
        result['matched_plane_relation']={status:sum(x['prediction'].get('focal_plane_relation','unknown')==status for x in detected)
                                           for status in ('same','different','unknown')}
        result['matched_mask_assessment']={status:sum(x['prediction'].get('mask_assessment','not_reviewed')==status for x in detected)
                                           for status in ('acceptable','unacceptable','merged','unsure','unavailable','not_reviewed')}
        for rank in ('genus','species'):
            eligible=[x for x in rows if x['reference'][rank+'_eligible']]
            detected=[x for x in eligible if x['prediction'] is not None]
            accepted=[x for x in detected if x['prediction'].get(rank) is not None]
            correct=sum(x['prediction'][rank]==x['reference'][rank] for x in accepted)
            correct_and_mask=sum(x['prediction'][rank]==x['reference'][rank] and x['prediction'].get('mask_assessment')=='acceptable' for x in accepted)
            mask_complete=bool(data.get('mask_rule_id')) and all(x['prediction'].get('mask_assessment','not_reviewed') in {'acceptable','unacceptable','unavailable'} for x in detected)
            result[rank]={'eligible':len(eligible),'correct':correct,'end_to_end_fraction':rate(correct,len(eligible)),
                          'correct_with_acceptable_mask':correct_and_mask,'mask_assessment_complete':mask_complete,
                          'correct_with_acceptable_mask_fraction':rate(correct_and_mask,len(eligible)) if mask_complete else None,
                          'missed':len(eligible)-len(detected),'detected_abstentions':len(detected)-len(accepted),
                          'accepted':len(accepted),'accuracy_among_accepted':rate(correct,len(accepted)),
                          'not_eligible':len(rows)-len(eligible)}
        return result
    strata={}
    for label,predicate in [('partial_yes',lambda r:r['partial']=='yes'),('partial_no',lambda r:r['partial']=='no'),
                            ('partial_unknown',lambda r:r['partial']=='unknown'),('overlap_group',lambda r:bool(r.get('overlap_group'))),
                            ('no_recorded_overlap_group',lambda r:not r.get('overlap_group'))]:
        strata[label]=summarize([x for x in all_rows if predicate(x['reference'])])
    def summarize_groups(groups):
        output={'groups':len(groups),'members':sum(len(g['members']) for g in groups),
                'fully_detected':sum(all(row['prediction'] is not None for row in g['members']) for g in groups),
                'fully_detected_with_nonempty_masks':sum(all(row['prediction'] is not None and row['prediction'].get('mask_status','unknown')=='nonempty'
                                                           for row in g['members']) for g in groups),
                'fully_detected_with_acceptable_masks':sum(all(row['prediction'] is not None and row['prediction'].get('mask_assessment','not_reviewed')=='acceptable'
                                                             for row in g['members']) for g in groups),
                'groups_with_unreviewed_matched_masks':sum(any(row['prediction'] is not None and row['prediction'].get('mask_assessment','not_reviewed')=='not_reviewed'
                                                               for row in g['members']) for g in groups),
                'groups_with_unsure_matched_masks':sum(any(row['prediction'] is not None and row['prediction'].get('mask_assessment','not_reviewed')=='unsure'
                                                           for row in g['members']) for g in groups),
                'groups_with_merged_matched_masks':sum(any(row['prediction'] is not None and row['prediction'].get('mask_assessment','not_reviewed')=='merged'
                                                           for row in g['members']) for g in groups),
                'groups_with_identified_merged_neighbors':sum(any(row['prediction'] is not None and any(neighbor in {x['reference']['id'] for x in g['members']}
                    for neighbor in row['prediction'].get('merged_reference_ids',[])) for row in g['members']) for g in groups),
                'groups_with_cross_plane_matches':sum(any(row['prediction'] is not None and row['prediction'].get('focal_plane_relation','unknown')=='different'
                                                           for row in g['members']) for g in groups)}
        for rank in ('genus','species'):
            eligible=[g for g in groups if all(row['reference'][rank+'_eligible'] for row in g['members'])]
            correct=sum(all(row['prediction'] is not None and row['prediction'].get(rank)==row['reference'][rank]
                            for row in g['members']) for g in eligible)
            output[rank]={'fully_eligible_groups':len(eligible),'fully_correct_groups':correct,
                          'fully_correct_fraction':rate(correct,len(eligible)),
                          'groups_with_ineligible_members':len(groups)-len(eligible)}
        return output
    def summarize_unmatched(rows):
        output={}
        for kind in ('duplicate','other','unknown'):
            selected=[row for row in rows if row['type']==kind];count=len(selected)
            output[kind]={'proposals':count}
            for rank in ('genus','species'):
                named=sum(row['prediction'].get(rank) is not None for row in selected)
                output[kind][rank]={'named':named,'unnamed':count-named,'named_fraction':rate(named,count)}
        return output
    def summarize_taxonomy(rows):
        return {status:sum(row['prediction'].get('taxonomy_status','not_checked')==status for row in rows)
                for status in ('consistent','conflicting','unmapped','not_applicable','not_checked')}
    per_taxon={}
    for rank in ('genus','species'):
        eligible=[row for row in all_rows if row['reference'][rank+'_eligible']]
        taxa=sorted({row['reference'][rank] for row in eligible})
        per_taxon[rank]={}
        for taxon in taxa:
            rows=[row for row in eligible if row['reference'][rank]==taxon]
            per_taxon[rank][taxon]={'sample_count':len({row['sample_id'] for row in rows}),
                                   'field_count':len({row['field_id'] for row in rows}),
                                   **summarize(rows)[rank]}
    return {'format':'diatom-instance-evaluation-result-v1','split':expected,'reference_status':review_status,'protocol_id':data['protocol_id'],'matching_rule_id':data['matching_rule_id'],'mask_rule_id':data.get('mask_rule_id'),
            'field_overlap_handling_id':field_overlap_rule,'overlapping_field_pairs':field_overlaps,
            'taxonomy_version':data['taxonomy_version'],'test_sample_count':len(test_samples),'field_count':len(fields),
            'overall':summarize(all_rows),'strata':strata,'per_sample':{sample:summarize([x for x in all_rows if x['sample_id']==sample]) for sample in sorted(test_samples)},
            'overlap_group_summary':summarize_groups(all_groups),
            'overlap_groups_per_sample':{sample:summarize_groups([g for g in all_groups if g['sample_id']==sample]) for sample in sorted(test_samples)},
            'per_taxon':per_taxon,'unmatched_name_summary':summarize_unmatched(all_unmatched),
            'unmatched_names_per_sample':{sample:summarize_unmatched([x for x in all_unmatched if x['sample_id']==sample]) for sample in sorted(test_samples)},
            'prediction_taxonomy_status':summarize_taxonomy(all_predictions),
            'prediction_taxonomy_per_sample':{sample:summarize_taxonomy([x for x in all_predictions if x['sample_id']==sample]) for sample in sorted(test_samples)},
            'fields':field_results,'warning':'Input review status, eligibility, taxonomy and independence are declarations, not verified facts. Target achievement is not established.'}


def main():
    p=argparse.ArgumentParser(description=__doc__);p.add_argument('--input',type=Path,required=True);p.add_argument('--output',type=Path,required=True)
    p.add_argument('--bootstrap-replicates',type=int,default=0,help='Optional sample-cluster bootstrap replicates (100–100000; default disabled)')
    p.add_argument('--bootstrap-seed',type=int,default=0)
    p.add_argument('--development',action='store_true',help='Score development validation fields; do not use held-out test for model selection')
    p.add_argument('--provisional',action='store_true',help='Allow provisional reviewer references and matches on development data only');a=p.parse_args()
    raw=a.input.read_bytes();result=evaluate(json.loads(raw),development=a.development,provisional=a.provisional);result['input_sha256']=hashlib.sha256(raw).hexdigest()
    if a.bootstrap_replicates:result['sample_cluster_bootstrap']=cluster_bootstrap(result['per_sample'],a.bootstrap_replicates,a.bootstrap_seed)
    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"Evaluated {result['overall']['instances']} declared reference instances; no target achievement is inferred.")


if __name__=='__main__':main()
