"""Profesor DeepSeek por lotes vLLM, con ocho muestras y checkpoints por problema."""
import argparse
import gzip
import hashlib
import importlib.metadata
import json
import os
from pathlib import Path
import time
os.environ.setdefault('VLLM_NO_USAGE_STATS','1')
os.environ.setdefault('DO_NOT_TRACK','1')
os.environ.setdefault('VLLM_WORKER_MULTIPROC_METHOD','spawn')
os.environ.setdefault('VLLM_USE_V2_MODEL_RUNNER','0')
os.environ.setdefault('VLLM_USE_FLASHINFER_SAMPLER','0')
from transformers import AutoTokenizer
import answer_extract_v2 as extractor
import train_generate_fast as extractor_helper

REV='ad9f0ae0864d7fbcd1cd905e3c6c5b069cc8b562'

def digest(path):
    h=hashlib.sha256()
    with Path(path).open('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('--model-path',required=True);ap.add_argument('--train-records',required=True);ap.add_argument('--output',required=True)
    ap.add_argument('--count',type=int,default=300);ap.add_argument('--samples',type=int,default=8)
    ap.add_argument('--max-tokens',type=int,default=1024);ap.add_argument('--kv-cache-mib',type=int,default=384)
    ap.add_argument('--max-model-length',type=int,default=1536);ap.add_argument('--gpu-memory-utilization',type=float,default=.55)
    ap.add_argument('--eager',action='store_true');args=ap.parse_args()
    base=Path(args.model_path);out=Path(args.output)
    if base.name!=REV or not 1<=args.count<=300 or args.samples<1 or args.max_tokens<1 or args.kv_cache_mib<1:ap.error('Modelo o parámetros incompatibles')
    records=json.loads(Path(args.train_records).read_text(encoding='utf8'))[:args.count]
    if len(records)!=args.count:raise ValueError('Faltan datos')
    tok=AutoTokenizer.from_pretrained(base,local_files_only=True)
    prompts=[]
    for row in records:
        prompt='Solve step by step. '+row['question']+'\nGive the final numerical answer on its own line as #### followed by the number.'
        ids=tok.apply_chat_template([{'role':'user','content':prompt}],add_generation_prompt=True,tokenize=True,return_dict=True)['input_ids']
        if len(ids)+args.max_tokens>args.max_model_length:raise ValueError('Ventana insuficiente')
        prompts.append(ids)
    protocol={'model_revision':REV,'model_sha256':digest(base/'model.safetensors'),
              'data_sha256':digest(args.train_records),'code_sha256':digest(__file__),
              'extractor_sha256':digest(extractor.__file__),'extractor_helper_sha256':digest(extractor_helper.__file__),
              'config_sha256':{name:digest(base/name) for name in ('config.json','tokenizer.json','tokenizer_config.json','generation_config.json')},
              'count':args.count,'samples':args.samples,'max_tokens':args.max_tokens,
              'temperature':.6,'top_p':.95,'top_k':-1,'seed_rule':'5100000 + problem*1000; n muestras por llamada',
              'backend':'vllm','vllm':importlib.metadata.version('vllm'),'kv_cache_mib':args.kv_cache_mib,
              'max_model_length':args.max_model_length,'gpu_memory_utilization':args.gpu_memory_utilization,'eager':args.eager,
              'enable_prefix_caching':True,
              'timing':'segundos de cada grupo divididos entre muestras; suma representa tiempo de generación de grupos'}
    out.mkdir(parents=True,exist_ok=True);meta=out/'protocol.json'
    if meta.exists() and json.loads(meta.read_text(encoding='utf8'))!=protocol:raise ValueError('Protocolo diferente')
    if not meta.exists():meta.write_text(json.dumps(protocol,indent=2,ensure_ascii=False),encoding='utf8')
    from vllm import LLM,SamplingParams
    llm=LLM(model=str(base),tokenizer=str(base),dtype='bfloat16',max_model_len=args.max_model_length,
            max_num_seqs=args.samples,kv_cache_memory_bytes=args.kv_cache_mib*1024*1024,
            gpu_memory_utilization=args.gpu_memory_utilization,enforce_eager=args.eager,enable_prefix_caching=True,seed=2026)
    for i,row in enumerate(records):
        file=out/f'problem-{i:04d}.json';ref=extractor.extract(row['answer'])
        if ref is None:raise ValueError('Referencia no extraída')
        if file.exists():
            previous=json.loads(file.read_text(encoding='utf8'))
            if len(previous)!=args.samples or any(x['question']!=row['question'] or x['reference']!=ref for x in previous):raise ValueError('Registro incompatible')
            continue
        params=SamplingParams(n=args.samples,temperature=.6,top_p=.95,top_k=-1,max_tokens=args.max_tokens,seed=5100000+i*1000)
        started=time.perf_counter();result=llm.generate([{'prompt_token_ids':prompts[i]}],params,use_tqdm=False)
        elapsed=time.perf_counter()-started
        if len(result)!=1 or len(result[0].outputs)!=args.samples:raise ValueError('Grupo incompleto')
        generated=[]
        for sample,completion in enumerate(result[0].outputs):
            if completion.index!=sample:raise ValueError('Índices de muestras desordenados')
            if completion.finish_reason not in ('stop','length'):raise ValueError('Motivo de parada desconocido')
            tokens=list(completion.token_ids);text='<think>\n'+tok.decode(tokens,skip_special_tokens=True)
            truncated=completion.finish_reason=='length';answer=extractor.extract(text,truncated=truncated)
            generated.append({'problem':i,'sample':sample,'question':row['question'],'reference':ref,'text':text,
                              'answer':answer,'truncated':truncated,'tokens_in':len(prompts[i]),
                              'tokens_out':len(tokens),'seconds':elapsed/args.samples})
        tmp=file.with_suffix('.tmp');tmp.write_text(json.dumps(generated,ensure_ascii=False),encoding='utf8');os.replace(tmp,file)
        print('profesor problema',i,'muestras',len(generated),'extraídas',sum(x['answer'] is not None for x in generated),flush=True)
    target=out/'teacher.jsonl.gz';tmp=out/'teacher.jsonl.gz.tmp'
    with gzip.open(tmp,'wt',encoding='utf8') as f:
        for i in range(args.count):
            for row in json.loads((out/f'problem-{i:04d}.json').read_text(encoding='utf8')):
                f.write(json.dumps(row,ensure_ascii=False)+'\n')
    os.replace(tmp,target)
    (out/'completed.json').write_text(json.dumps({'teacher_sha256':digest(target)},indent=2),encoding='utf8')
    print('Corpus profesor completado',flush=True)

if __name__=='__main__':main()
