"""Acuerdo con 50 anotaciones del asistente; no es evaluación humana."""
from collections import Counter
import json
import sys

LABELS=('exito','final','formato','herramienta','observacion')


def summarize(rows):
    if len(rows)!=50 or {r['index'] for r in rows}!=set(range(50)):
        raise ValueError('se necesitan exactamente 50 registros únicos')
    if len({(r['model'],r['revision']) for r in rows})!=1:
        raise ValueError('modelos mezclados')
    if any(r['reference_annotator']!='assistant' or r['reference'] not in LABELS for r in rows):
        raise ValueError('referencias inesperadas')
    matrix=Counter((r['reference'],r['prediction']) for r in rows)
    predictions=sorted({r['prediction'] for r in rows})
    agreement=sum(r['reference']==r['prediction'] for r in rows)/len(rows)
    breakdown={}
    for label in LABELS:
        tp=matrix[label,label]
        true=sum(1 for r in rows if r['reference']==label)
        predicted=sum(1 for r in rows if r['prediction']==label)
        breakdown[label]={'support':true,'predicted':predicted,
                          'recall':tp/true if true else None,'precision':tp/predicted if predicted else None}
    return {'n':len(rows),'agreement':agreement,'matrix':{ref:{pred:matrix[ref,pred] for pred in predictions} for ref in LABELS},
            'classes':breakdown,'invalid':sum(r['prediction'].startswith('invalid_') for r in rows),
            'reference':'assistant annotations, not human or independent',
            'caveat':'small selected sample; checker success shown to judge; no ground-truth causal diagnosis'}


if __name__=='__main__':
    with open(sys.argv[1],encoding='utf-8') as stream: rows=[json.loads(line) for line in stream]
    print(json.dumps(summarize(rows),ensure_ascii=False,indent=2))
