"""Recalcula la localización a partir de puntuaciones guardadas y referencias.

Comprueba identidades, hashes y agregados; no vuelve a ejecutar la red ni
certifica por sí mismo la validez matemática de una anotación.
"""
import argparse
import hashlib
import json
import math
from pathlib import Path
from evaluate_first_error import summarize_rows

def digest(path):
    h=hashlib.sha256()
    with Path(path).open('rb') as stream:
        for block in iter(lambda:stream.read(1024*1024),b''):h.update(block)
    return h.hexdigest()

def main():
    ap=argparse.ArgumentParser();ap.add_argument('--data',required=True);ap.add_argument('--result',required=True)
    ap.add_argument('--adapter',required=True);ap.add_argument('--output',required=True);args=ap.parse_args()
    source=json.loads(Path(args.data).read_text(encoding='utf8'));result=json.loads(Path(args.result).read_text(encoding='utf8'))
    rows=result['rows'];training=json.loads((Path(args.adapter)/'training.json').read_text(encoding='utf8'))
    if len(source)!=50 or len(rows)!=50 or len({x['question'] for x in source})!=50:raise ValueError('Casos incompletos')
    if result['dataset_sha256']!=digest(args.data) or result['adapter_sha256']!=digest(Path(args.adapter)/'adapter_model.safetensors') or result['adapter_sha256']!=training['adapter_sha256'] or training.get('scope')!='full':raise ValueError('Fuentes o adaptador no coinciden')
    for truth,row in zip(source,rows):
        scores=row['scores']
        if (len(scores)!=len(truth['steps']) or not scores or any(not isinstance(x,(int,float)) or not math.isfinite(x) or not 0<=x<=1 for x in scores) or
            row['reference_first_error']!=truth['first_error'] or row['scorable']!=truth.get('scorable',True) or row['ambiguous']!=truth.get('ambiguous',False) or
            row['predicted']!=min(range(len(scores)),key=lambda i:scores[i]) or not 0<=row['prefixes_truncated']<=len(scores)):
            raise ValueError('Puntuaciones o referencia alteradas')
    expected=summarize_rows(rows)
    if any(result.get(key)!=value for key,value in expected.items()) or result['prefixes_truncated']!=sum(x['prefixes_truncated'] for x in rows):raise ValueError('El resumen no se reconstruye')
    out={'scope':'Recalcula selección y resúmenes; no ejecuta la red ni valida las anotaciones.','cases':50,'scorable_error_cases':expected['n_with_error'],
         'dataset_sha256':digest(args.data),'result_sha256':digest(args.result),'adapter_sha256':result['adapter_sha256'],'auditor_sha256':digest(__file__)}
    Path(args.output).write_text(json.dumps(out,indent=2),encoding='utf8')
    print('Primer error auditado:',len(rows),'casos;',expected['n_with_error'],'con error puntuable')

if __name__=='__main__':main()
