"""Count how many name / jargon mentions survive in a transcript set.
A mention counts as correct if the transcript of that memo contains the term exactly as many times as the script does
(case-insensitive, spaces ignored for Latin terms). Usage: score_names.py transcripts_grok.json [...]"""
import json, pathlib, sys
HERE = pathlib.Path(__file__).resolve().parent
d = json.load(open(HERE / 'memos.json', encoding='utf-8'))
NAMES, TERMS = list(d['people']), [t for t in d['terms'] if t != 'Apple']
norm = lambda s: s.lower().replace(' ', '')

def score(trans, vocab):
    tot = hit = 0; misses = {}
    for m in d['memos']:
        ref, hyp = norm(m['text']), norm(trans.get(m['id'], ''))
        for v in vocab:
            n = ref.count(norm(v))
            if not n: continue
            k = min(n, hyp.count(norm(v)))
            tot += n; hit += k
            if k < n: misses.setdefault(v, 0); misses[v] += n - k
    return tot, hit, misses

if __name__ == '__main__':
    out = {}
    for f in sys.argv[1:] or sorted(p.name for p in HERE.glob('transcripts_*.json')):
        t = json.load(open(HERE / f, encoding='utf-8'))
        for label, vocab in [('names', NAMES), ('terms', TERMS)]:
            tot, hit, miss = score(t, vocab)
            out[f'{f}:{label}'] = {'total': tot, 'correct': hit, 'misses': miss}
            print(f'{f:28s} {label:5s} {hit}/{tot}  misses={miss}')
    json.dump(out, open(HERE / 'name_scores.json', 'w', encoding='utf-8'), ensure_ascii=False, indent=1)
