<filename>src/bratdb/funcs/info.py
"""
Describe and provide information about the files
    generated by the bratdb package.
"""
from collections import Counter

from bratdb.funcs.utils import get_output_path, load_brat_dump


def get_brat_info(bratdb, **kwargs):
    brat = load_brat_dump(bratdb)
    n_sents = 0
    n_sents_min = None
    n_sents_max = 0
    n_docs = brat.doc_count
    n_annots = 0
    n_annots_min = 0
    n_annots_max = 0
    annot_cntr = Counter()
    n_dupes = 0
    for name, annots, sents in brat:
        n_sents += len(sents)
        if n_sents_min is None or len(sents) < n_sents_min:
            n_sents_min = len(sents)
        if len(sents) > n_sents_max:
            n_sents_max = len(sents)
        if len(annots) > 1:
            n_dupes += 1
        if n_annots_min is None or len(annots[0]) < n_annots_min:
            n_annots_min = len(annots[0])
        if len(annots[0]) > n_annots_max:
            n_annots_max = len(annots[0])
        for ann in annots[0].values():
            n_annots += 1
            for label in ann.labels:
                annot_cntr[label] += 1
    annot_cnt = [(f'Annot:{label}', cnt) for label, cnt in annot_cntr.items()]
    return [
               ('Documents', n_docs),
               ('Sentences', n_sents),
               ('Max Sentences in a document', n_sents_max),
               ('Min Sentences in a document', n_sents_min),
               ('Sentence/document', n_sents / n_docs),
               ('Annotations', n_annots),
               ('Max Annotations in a document', n_annots_max),
               ('Min Annotations in a document', n_annots_min),
               ('Annotations/document', n_annots / n_docs),
               ('Duplicate Annotations', n_annots),
           ] + annot_cnt


def build_bratdb_info_file(bratdb, *, outpath=None, **kwargs):
    outpath = get_output_path(bratdb, outpath, exts=('info', 'txt'))
    data = get_brat_info(bratdb, **kwargs)
    with open(outpath, 'w') as out:
        for key, value in data:
            out.write(f'{key:.<30}.{value}\n')
