"""Score a system on Kitaab's reply corpus.

    python3 score.py corpus.json predictions.jsonl [--omega 30] [--alpha 1]

predictions.jsonl has one JSON object per line:
    {"id": "<corpus item id>", "family": "<one of the seven families>", "agreement": true | false}

"family" is what the reply does. "agreement" answers: if this reply came back to a
specific proposal (a price, a date, a quantity), could a careful system record it as
agreement without asking? In this edition the answer is yes only for replies whose
family is "Agreement, if specific".

The cost treats a false agreement as omega times worse than an unnecessary
question (alpha), as in The Handshake, Appendix B2 (kitaab.live/research/the-handshake):
a wrong yes recorded against a client costs far more than one more message.
The labels in this edition are Kitaab's own readings, not yet independently
labelled by native speakers; read the scores in that light.
"""
import json
import sys
from collections import defaultdict

FAMILIES = ['Acknowledgement', 'Agreement, if specific', 'Deferral', 'Polite refusal', 'Counter', 'Expressive', 'Unclear']


def main(argv):
    if len(argv) < 3:
        sys.exit(__doc__)
    omega = float(argv[argv.index('--omega') + 1]) if '--omega' in argv else 30.0
    alpha = float(argv[argv.index('--alpha') + 1]) if '--alpha' in argv else 1.0
    corpus = {i['id']: i for i in json.load(open(argv[1], encoding='utf-8'))['items']}
    preds = {}
    for n, line in enumerate(open(argv[2], encoding='utf-8'), 1):
        if not line.strip():
            continue
        p = json.loads(line)
        if p.get('id') not in corpus:
            sys.exit(f'line {n}: unknown id {p.get("id")!r}')
        if p.get('family') not in FAMILIES:
            sys.exit(f'line {n}: family must be one of {FAMILIES}')
        if not isinstance(p.get('agreement'), bool):
            sys.exit(f'line {n}: agreement must be true or false')
        preds[p['id']] = p
    missing = [i for i in corpus if i not in preds]
    if missing:
        print(f'warning: {len(missing)} items have no prediction and count as wrong', file=sys.stderr)

    right = false_yes = needless_asks = 0
    by_lang = defaultdict(lambda: [0, 0])
    confusion = defaultdict(int)
    for iid, item in corpus.items():
        gold_family = item['family']
        gold_agree = gold_family == 'Agreement, if specific'
        p = preds.get(iid, {'family': None, 'agreement': not gold_agree})
        ok = p['family'] == gold_family
        right += ok
        by_lang[item['language_name']][0] += ok
        by_lang[item['language_name']][1] += 1
        confusion[(gold_family, p['family'])] += 1
        if p['agreement'] and not gold_agree:
            false_yes += 1
        if not p['agreement'] and gold_agree:
            needless_asks += 1

    n = len(corpus)
    cost = omega * false_yes + alpha * needless_asks
    print(f'items: {n}')
    print(f'family accuracy: {right / n:.3f}')
    print(f'false agreements (recorded a yes that was not one): {false_yes}')
    print(f'needless questions (asked when the yes was clear): {needless_asks}')
    print(f'cost at omega={omega:g}, alpha={alpha:g}: {cost:g} ({cost / n:.3f} per item; 0 is perfect)')
    print('family accuracy by language:')
    for lang, (r, t) in sorted(by_lang.items()):
        print(f'  {lang}: {r}/{t}')
    print('confusions (gold -> predicted, count):')
    for (g, pr), c in sorted(confusion.items(), key=lambda kv: -kv[1]):
        if g != pr:
            print(f'  {g} -> {pr}: {c}')


if __name__ == '__main__':
    main(sys.argv)
