"""Audita las 600 salidas híbridas y recalcula la evaluación sobre MATH-500."""
import argparse
import hashlib
import json
from pathlib import Path
import random
from transformers import AutoTokenizer,GenerationConfig

import hybrid_modes_vllm as experiment
import math_eval


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


def interval(values):
    rng=random.Random(73)
    draws=sorted(sum(rng.choice(values) for _ in values)/len(values) for _ in range(2000))
    return [draws[49],draws[1949]]


def main():
    ap=argparse.ArgumentParser();ap.add_argument('--run',required=True);ap.add_argument('--data',required=True)
    ap.add_argument('--model-path',required=True)
    ap.add_argument('--output',required=True);args=ap.parse_args()
    root=Path(args.run);data=Path(args.data);base=Path(args.model_path)
    protocol=json.loads((root/'protocol.json').read_text(encoding='utf8'))
    summary=json.loads((root/'summary.json').read_text(encoding='utf8'))
    if (digest(data)!=experiment.DATA_SHA or protocol['data_sha256']!=experiment.DATA_SHA or
        protocol['data_revision']!=experiment.DATA_REV or protocol['revision']!=experiment.REV or
        protocol['weights']!=experiment.WEIGHTS or base.name!=experiment.REV or protocol['rows']!=[0,199] or
        protocol['conditions']!=experiment.CONDITIONS or protocol['backend']!='vllm' or
        protocol['answer_tokens']!=256 or protocol['code_sha256']!=digest(experiment.__file__) or
        protocol['grader_sha256']!=digest(math_eval.__file__)):
        raise ValueError('El protocolo no coincide con la campaña fijada')
    expected_settings={'temperature':.6,'top_p':.95,'top_k':-1,'batch':4,'kv_cache_mib':1024,
                       'max_model_length':2048,'eager':False,'math_verify':'0.9.0',
                       'seed_rule':'920000 + problem; answer after thought uses offset 10000000'}
    if any(protocol.get(key)!=value for key,value in expected_settings.items()):
        raise ValueError('Los parámetros de generación no coinciden con el diseño fijado')
    metadata=('config.json','generation_config.json','tokenizer.json','tokenizer_config.json','vocab.json','merges.txt')
    if protocol['model_metadata_sha256']!={name:digest(base/name) for name in metadata}:
        raise ValueError('Metadatos o tokenizador diferentes')
    tok=AutoTokenizer.from_pretrained(base,local_files_only=True)
    opening=tok.encode('<think>',add_special_tokens=False);closing=tok.encode('</think>',add_special_tokens=False)
    if (len(opening)!=1 or len(closing)!=1 or protocol.get('think_open_token_id')!=opening[0] or
        protocol.get('think_close_token_id')!=closing[0]):raise ValueError('Delimitadores de pensamiento distintos')
    eos=GenerationConfig.from_pretrained(base,local_files_only=True).eos_token_id
    eos_ids=set(eos if isinstance(eos,list) else [eos])|{tok.eos_token_id}
    source=[json.loads(line) for line in data.read_text(encoding='utf8').splitlines() if line.strip()][:200]
    if len(source)!=200:raise ValueError('Datos reservados incompletos')
    hashes={};rows={}
    for name,cap in experiment.CONDITIONS.items():
        rows[name]=[]
        for i,truth in enumerate(source):
            path=root/f'{i:03d}-{name}.json';row=json.loads(path.read_text(encoding='utf8'))
            if (row['problem']!=i or row['condition']!=name or row['unique_id']!=truth['unique_id'] or
                row['level']!=truth['level'] or row['gold']!=truth['answer'] or
                row['correct']!=math_eval.grade(truth['answer'],row['answer'])):
                raise ValueError(f'Identidad, referencia o nota incorrecta: {path.name}')
            if (row['input_tokens']<1 or row['thought_tokens']<0 or row['answer_tokens']<0 or
                row['answer_tokens']>256 or row['seconds']<0 or row['batch_wall_seconds']<row['seconds'] or
                row['answer_finish_reason'] not in ('stop','length')):
                raise ValueError(f'Contadores o fin de respuesta inválidos: {path.name}')
            if (len(row['thought_token_ids'])!=row['thought_tokens'] or len(row['answer_token_ids'])!=row['answer_tokens'] or
                tok.decode(row['thought_token_ids'],skip_special_tokens=True)!=row['thought'] or
                tok.decode(row['answer_token_ids'],skip_special_tokens=True)!=row['answer'] or
                row['unexpected_thought']!=(cap is None and opening[0] in row['answer_token_ids'])):
                raise ValueError(f'Tokens, texto o delimitador incompatibles: {path.name}')
            prompt='Solve the problem and give the final answer in a LaTeX box.\n'+truth['problem']
            ids=tok.apply_chat_template([{'role':'user','content':prompt}],add_generation_prompt=True,
                                        enable_thinking=cap is not None,tokenize=True,return_dict=True)['input_ids']
            if row['input_tokens']!=len(ids):raise ValueError(f'Longitud de prompt incompatible: {path.name}')
            if cap is None:
                if row['thought_tokens']!=0 or row['thought_raw_token_ids'] or row['forced_close'] or row['thought_finish_reason'] is not None or row['closing_tokens']!=0:
                    raise ValueError(f'Traza sin pensamiento incompatible: {path.name}')
            elif (row['thought_tokens']>cap or row['closing_tokens']!=1 or
                  row['thought_finish_reason'] not in ('stop','length')):
                raise ValueError(f'Contador o fin de pensamiento inválido: {path.name}')
            else:
                raw=row['thought_raw_token_ids'];closed=row['thought_stop_reason']==closing[0] or bool(raw and raw[-1]==closing[0])
                trimmed=raw[:-1] if raw and (raw[-1]==closing[0] or raw[-1] in eos_ids) else raw
                if len(raw)>cap or row['forced_close']==closed or trimmed!=row['thought_token_ids']:
                    raise ValueError(f'Cierre de pensamiento incompatible: {path.name}')
            hashes[path.name]=digest(path);rows[name].append(row)
        group=rows[name];values=[int(r['correct'] is True) for r in group]
        known=[r for r in group if r['correct'] is not None]
        expected={'accuracy_abstentions_counted_zero':sum(values)/len(values),
                  'accuracy_among_parsed':sum(r['correct'] is True for r in known)/len(known) if known else None,
                  'abstentions':len(group)-len(known),'bootstrap_95':interval(values),
                  'unexpected_thought':sum(r['unexpected_thought'] for r in group),
                  'forced_close':sum(r['forced_close'] for r in group),
                  'thought_limit':sum(r['thought_finish_reason']=='length' for r in group),
                  'answer_limit':sum(r['answer_finish_reason']=='length' for r in group),
                  'mean_thought_tokens':sum(r['thought_tokens'] for r in group)/len(group),
                  'mean_seconds':sum(r['seconds'] for r in group)/len(group),
                  'mean_batch_wall_seconds':sum(r['batch_wall_seconds'] for r in group)/len(group)}
        if summary[name]!=expected:raise ValueError(f'Resumen incompatible: {name}')
    base=rows['sin_pensamiento']
    for name in ('pensamiento_256','pensamiento_1024'):
        diffs=[int(b['correct'] is True)-int(a['correct'] is True) for a,b in zip(base,rows[name])]
        expected={'mean':sum(diffs)/len(diffs),'bootstrap_95':interval(diffs)}
        if summary['paired_differences'][name]!=expected:raise ValueError('Contraste pareado incompatible')
    report={'scope':'600 respuestas generadas; la extracción y comparación matemática se reproducen, no certifican los pasos',
            'rows':len(hashes),'protocol_sha256':digest(root/'protocol.json'),'summary_sha256':digest(root/'summary.json'),
            'source_sha256':digest(data),'auditor_sha256':digest(__file__),'records_sha256':hashes}
    target=Path(args.output);target.parent.mkdir(parents=True,exist_ok=True)
    target.write_text(json.dumps(report,ensure_ascii=False,indent=2),encoding='utf8')
    print('Auditoría completa:',len(hashes),'filas; sumarios y contrastes reproducidos')


if __name__=='__main__':main()
