"""Prepara revisión manual explícita de 40 errores por método."""
import json
import sys
from pathlib import Path

def prepare(rows,per_method=40):
    result=[]
    for method in ('cot','pal'):
        failures=[row for row in rows if row['method']==method and row['correct'] is False]
        if len(failures)<per_method:raise ValueError(f'{method}: not enough failures')
        families=sorted({r['family'] for r in failures})
        groups={family:[r for r in failures if r['family']==family] for family in families}
        chosen=[]
        while len(chosen)<per_method:
            progress=False
            for family in families:
                if groups[family] and len(chosen)<per_method:
                    chosen.append(groups[family].pop(0));progress=True
            if not progress:raise ValueError('selection could not be completed')
        for row in chosen:
            result.append({'id':row['id'],'method':method,'family':row['family'],
                           'category':None,'reason':None,'annotator':None})
    return result

def validate(annotations,rows,per_method=40):
    if len(annotations)!=2*per_method:raise ValueError('incorrect count')
    for method in ('cot','pal'):
        method_rows=[r for r in annotations if r['method']==method]
        if len(method_rows)!=per_method or len({r['id'] for r in method_rows})!=per_method:raise ValueError('incomplete or duplicate')
    for row in annotations:
        source=[r for r in rows if (r['id'],r['method'],r['family'])==(row['id'],row['method'],row['family'])]
        if len(source)!=1 or source[0]['correct'] is not False:raise ValueError('not a unique observed failure')
        if row['category'] not in ('calculo','planteamiento','formato','ejecucion','rechazo_filtro','ambiguo'):
            raise ValueError('unreviewed or unknown category')
        if row['annotator']!='assistant' or not isinstance(row['reason'],str) or len(row['reason'].strip())<15:
            raise ValueError('reviewer and trace-specific rationale required')
    return True

if __name__=='__main__':
    if len(sys.argv)!=4 or sys.argv[1] not in ('prepare','validate'):
        raise SystemExit('usage: annotate_errors.py prepare|validate results.jsonl annotations.json')
    mode,source,destination=sys.argv[1:]
    if mode=='prepare':
        path=Path(destination)
        if path.exists():raise ValueError('do not overwrite annotations')
        with open(source,encoding='utf8') as f:lines=[json.loads(line) for line in f]
        path.write_text(json.dumps(prepare(lines[1:]),ensure_ascii=False,indent=2),encoding='utf8')
    else:
        with open(destination,encoding='utf8') as f:items=json.load(f)
        with open(source,encoding='utf8') as f:lines=[json.loads(line) for line in f]
        validate(items,lines[1:]);print('80 anotaciones completas del asistente')
