"""Reconstruct the original BC5CDR document-level comparison; prints aggregates only."""
import argparse
import hashlib
import json
from pathlib import Path
import zipfile

from link import CDR_SHA256, MESH_INDEX_SHA256, load_encoder, load_inputs, sha
from linking import bioc, blind_projection, predict
from measurement import score_rows, summarize

PREFIX='CDR_Data/CDR.Corpus.v010516/CDR_'


def confirmation_decision(report):
    s=report['slices']
    required=('all','Chemical','Disease','non_abbreviation','known_index')
    if not all(s[k]['documents']>=30 for k in required):return 'stop_or_insufficient_evidence'
    if not all(s[k]['lower_95'] is not None and s[k]['lower_95']>=-.02 for k in required[1:]):
        return 'stop_or_insufficient_evidence'
    all_docs=s['all']
    return ('confirmed_within_scope' if all_docs['mean_difference']>=.02 and
            all_docs['lower_95'] is not None and all_docs['lower_95']>0 else 'stop_or_insufficient_evidence')



def check_split_identity(train, dev, test=None):
    if set(train)&set(dev):
        raise ValueError('Training and development document identities overlap.')
    if test is not None:
        if set(train)&set(test) or set(dev)&set(test):
            raise ValueError('Test document identities overlap another split.')
        def text_ids(docs):
            return {hashlib.sha256(text.encode('utf-8')).digest() for text,_ in docs.values()}
        test_texts=text_ids(test)
        if len(test_texts)!=len(test) or test_texts&(text_ids(train)|text_ids(dev)):
            raise ValueError('A test document exactly duplicates another test or a training or development text.')

def evaluate(cdr,index_path,split,embed):
    if split not in ('development','test','train-parity'):
        raise ValueError('Specify an allowed split explicitly.')
    if sha(cdr)!=CDR_SHA256 or sha(index_path)!=MESH_INDEX_SHA256:
        raise ValueError('The BC5CDR archive or descriptor index has changed.')
    lex,index=load_inputs(cdr,index_path)
    with zipfile.ZipFile(cdr) as archive:
        train=bioc(archive.read(PREFIX+'TrainingSet.BioC.xml'))
        if len(train)!=500:
            raise ValueError('Unexpected training split.')
        if split=='train-parity':
            docs=train
        else:
            dev=bioc(archive.read(PREFIX+'DevelopmentSet.BioC.xml'))
            if len(dev)!=500:
                raise ValueError('Unexpected development split.')
            if split=='test':
                docs=bioc(archive.read(PREFIX+'TestSet.BioC.xml'))
                if len(docs)!=500:
                    raise ValueError('Unexpected test split.')
                check_split_identity(train,dev,docs)
            else:
                docs=dev
                check_split_identity(train,dev)
    if sum(len(a) for _,a in docs.values())>12000:
        raise ValueError('Unexpected source exposure bound.')
    if split=='train-parity':
        ordered=sorted(docs,key=lambda x:hashlib.sha256(('sapbert-release-parity-v1:'+x).encode()).digest())[:32]
        docs={key:docs[key] for key in ordered}
    inputs,keys=blind_projection(docs,lex)
    if split=='train-parity':inputs,keys=inputs[:256],keys[:256]
    predictions=predict(inputs,lex,embed)
    rows=score_rows(index,inputs,keys,predictions,lex)
    report=summarize(rows,sum(not a[3] for _,ann in docs.values() for a in ann))
    if split=='test':report['eligibility']=confirmation_decision(report)
    if split=='train-parity':report['eligibility']='not_a_scientific_decision'
    report.update(phase=split,source_documents=len(docs),parity_fixture_only=(split=='train-parity'))
    return report


def main():
    p=argparse.ArgumentParser(description=__doc__)
    p.add_argument('--cdr',required=True,type=Path,help='Original BC5CDR CDR_Data.zip; not distributed here.')
    p.add_argument('--split',required=True,choices=('development','test','train-parity'))
    p.add_argument('--model-dir',type=Path)
    p.add_argument('--device',default='cpu',choices=('cpu','cuda'))
    args=p.parse_args()
    report=evaluate(args.cdr,Path(__file__).with_name('mesh2016_index.json'),args.split,
                    load_encoder(args.model_dir,args.device))
    print(json.dumps(report,sort_keys=True,indent=2))


if __name__=='__main__':main()
