"""Etiquetas Monte Carlo de prefijos de GSM8K; salida reanudable por prefijo.

Requiere los scripts answer_extract_v2.py y train_generate_fast.py de m23-l05
en el mismo directorio. Ejecutar --help para los parámetros.
"""
import argparse
import gzip
import hashlib
import json
from pathlib import Path

import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
import answer_extract_v2 as extractor

REV = '989aa7980e4cf806f80c7fef2b1adb7bc71aa306'
SOURCE_SHA = '9b455bdf65e2766014d96ca0c1927040d36493f267f0b62f0e760bb925a4757b'

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

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument('--samples', required=True, help='orm_train_hf_b256.jsonl.gz de m23-l05')
    ap.add_argument('--model-path', required=True)
    ap.add_argument('--output', required=True)
    ap.add_argument('--problems', type=int, default=300)
    ap.add_argument('--rollouts', type=int, default=8)
    ap.add_argument('--max-new-tokens', type=int, default=256)
    args = ap.parse_args()
    if not 1 <= args.problems <= 300 or args.rollouts != 8:
        ap.error('Se admiten hasta 300 problemas y exactamente 8 despliegues')
    if Path(args.model_path).name != REV:
        ap.error('Usa la revisión fijada de Qwen2.5-1.5B-Instruct')
    if digest(args.samples) != SOURCE_SHA:
        raise ValueError('El archivo no es el corpus publicado de m23-l05')
    if not torch.cuda.is_available():
        raise RuntimeError('Este laboratorio requiere CUDA')
    model_path = Path(args.model_path)
    out = Path(args.output)
    out.mkdir(parents=True, exist_ok=True)
    files = ['config.json','tokenizer.json','tokenizer_config.json','model.safetensors']
    protocol = {'model_revision':REV, 'model_sha256':{name:digest(model_path/name) for name in files},
                'samples_sha256':digest(args.samples), 'code_sha256':digest(__file__),
                'extractor_sha256':digest(extractor.__file__),
                'problems':args.problems, 'rollouts':args.rollouts,
                'max_new_tokens':args.max_new_tokens, 'torch':torch.__version__,
                'device':torch.cuda.get_device_name(), 'seed_rule':'230000 + 1000*problem + step'}
    meta = out/'protocol.json'
    if meta.exists() and json.loads(meta.read_text(encoding='utf8')) != protocol:
        raise ValueError('El protocolo no coincide con la salida existente')
    if not meta.exists(): meta.write_text(json.dumps(protocol,indent=2,ensure_ascii=False),encoding='utf8')
    with gzip.open(args.samples,'rt',encoding='utf8') as f:
        rows = [json.loads(line) for line in f if line.strip()]
    selected = [row for row in rows if row['problem'] < args.problems and row['sample'] == 0]
    selected.sort(key=lambda x:x['problem'])
    if [r['problem'] for r in selected] != list(range(args.problems)):
        raise ValueError('Falta alguna solución original')
    tok = AutoTokenizer.from_pretrained(model_path,local_files_only=True)
    tok.pad_token = tok.eos_token
    model = AutoModelForCausalLM.from_pretrained(model_path,dtype=torch.bfloat16,local_files_only=True).to('cuda').eval()
    eos=model.generation_config.eos_token_id
    eos_ids=set(eos if isinstance(eos,list) else [eos]) | {tok.eos_token_id}
    for row in selected:
        lines = [line for line in row['text'].splitlines() if line.strip()]
        for step in range(len(lines)):
            target = out/f"p{row['problem']:04d}-s{step:04d}.json"
            prefix = '\n'.join(lines[:step+1])
            if target.exists():
                saved = json.loads(target.read_text(encoding='utf8'))
                if saved['prefix'] != prefix or len(saved['continuations']) != args.rollouts:
                    raise ValueError(f'Prefijo previo incompatible: {target}')
                continue
            question = ('Solve step by step. '+row['question']+
                        '\nGive the final numerical answer on its own line as #### followed by the number.')
            messages = [{'role':'user','content':question},{'role':'assistant','content':prefix}]
            prompt = tok.apply_chat_template(messages,tokenize=False,continue_final_message=True)
            encoded = tok(prompt,return_tensors='pt').to('cuda')
            ids = encoded['input_ids'].repeat(args.rollouts,1)
            mask = encoded['attention_mask'].repeat(args.rollouts,1)
            torch.manual_seed(230000+1000*row['problem']+step)
            with torch.inference_mode():
                generated = model.generate(input_ids=ids,attention_mask=mask,do_sample=True,
                    temperature=.8,top_p=.9,top_k=0,repetition_penalty=1.1,
                    max_new_tokens=args.max_new_tokens,pad_token_id=tok.eos_token_id)
            continuations = []
            for seq in generated:
                tokens = seq[ids.shape[1]:].tolist()
                stop=next((i for i,t in enumerate(tokens) if t in eos_ids),None)
                if stop is not None: tokens=tokens[:stop+1]
                truncated = stop is None and len(tokens) >= args.max_new_tokens
                text = tok.decode(tokens,skip_special_tokens=True)
                answer = extractor.extract(prefix+text,truncated=truncated)
                continuations.append({'text':text,'answer':answer,'truncated':truncated,
                                      'correct':None if answer is None else int(answer==row['reference'])})
            record = {'problem':row['problem'],'step':step,'question':row['question'],
                      'reference':row['reference'],'prefix':prefix,'continuations':continuations}
            tmp = target.with_suffix('.tmp')
            tmp.write_text(json.dumps(record,ensure_ascii=False),encoding='utf8')
            tmp.replace(target)
            print('problema',row['problem'],'paso',step+1,'de',len(lines),flush=True)

if __name__ == '__main__': main()
