"""Selector universal y voraz sobre la campaña B32, para un motor vLLM existente.

Los problemas completados se guardan de forma atómica. El modelo y las
muestras son distintos de la campaña de entrenamiento del ORM; solo se comparte
la carga del motor causal. No compara bit a bit con Transformers.
"""
import hashlib,json,os,random,re,uuid
from decimal import Decimal,InvalidOperation
from pathlib import Path
MODEL='Qwen/Qwen2.5-1.5B-Instruct'
REV='989aa7980e4cf806f80c7fef2b1adb7bc71aa306'
KS=[0,1,2,4,8,16,32,64]

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

def atomic_write(path,content):
    path=Path(path);tmp=path.with_name(path.name+'.tmp-'+uuid.uuid4().hex)
    with tmp.open('xb') as f:f.write(content);f.flush();os.fsync(f.fileno())
    os.replace(tmp,path)

def extract(text):
    number=r'[+-]?(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?(?![\d,]|\.\d)'
    hits=re.findall(r'####\s*\$?\s*('+number+r')',text)
    if not hits:hits=re.findall(r'\\boxed\{\s*('+number+r')\s*\}',text)
    if not hits:hits=re.findall(r'(?i)\b(?:the\s+)?answer\s+is\s*[:$]?\s*('+number+r')',text)
    if not hits:hits=re.findall(r'(?i)\b(?:the\s+)?final\s+(?:number|answer)\s+(?:is\s*)?[:]?\s*\*{0,2}\$?\s*('+number+r')',text)
    if not hits:
        m=re.fullmatch(r'\s*\$?\s*('+number+r')\s*(?:[A-Za-z%]+)?[.\s]*',text)
        hits=[m.group(1)] if m else []
    try:return str(Decimal(hits[-1].replace(',','')).normalize()) if hits else None
    except InvalidOperation:return None

def load_samples(path):
    rows=[json.loads(x) for x in Path(path).read_text(encoding='utf8').splitlines()]
    groups={i:[] for i in range(200)}
    for r in rows:
        if r['problema'] not in groups:raise ValueError('Problema fuera de rango')
        groups[r['problema']].append(r)
    for group in groups.values():
        if sorted(r['muestra'] for r in group)!=list(range(64)):raise ValueError('Muestras duplicadas o incompletas')
        if any(r.get('lote')!=32 or r.get('puntuacion')!='logits_originales_stream' for r in group):
            raise ValueError('Protocolo original distinto')
        if any(extract(r['texto'])!=r['respuesta'] for r in group):raise ValueError('Extractor original no coincide')
        group.sort(key=lambda r:r['muestra'])
    return groups

def prompts_for(i,group,tok):
    prompts=[];candidates=[]
    for k in KS:
        if k==0:
            chosen=[]
            message='Solve step by step. '+group[0]['pregunta']+'\nGive the final numerical answer on its own line as #### followed by the number.'
        else:
            chosen=random.Random(1000*i+k).sample(group,k)
            listing='\n\n'.join(str(j+1)+'. '+r['texto'] for j,r in enumerate(chosen))
            message='Choose the candidate most consistent with the others. Return only its integer number.\nQuestion: '+group[0]['pregunta']+'\nCandidates:\n'+listing
        rendered=tok.apply_chat_template([{'role':'user','content':message}],tokenize=False,add_generation_prompt=True)
        ids=tok(rendered,add_special_tokens=False)['input_ids']
        if len(ids)+(256 if k==0 else 32)>17000:raise ValueError('La ventana de 17000 no cubre el prompt')
        prompts.append({'prompt_token_ids':ids});candidates.append(chosen)
    return prompts,candidates

def check_problem(i,rows,group,tok):
    if len(rows)!=len(KS) or sorted(r['k'] for r in rows)!=KS:raise ValueError('Checkpoint incompleto o duplicado')
    prompts,candidates=prompts_for(i,group,tok)
    by_k={r['k']:r for r in rows};reference=group[0]['referencia']
    for index,k in enumerate(KS):
        row=by_k[k];chosen=candidates[index];text=row['texto']
        if k==0:
            choice=None;answer=extract(text)
        else:
            match=re.fullmatch(r'\s*(\d+)\s*[.\s]*',text)
            choice=int(match.group(1))-1 if match and 1<=int(match.group(1))<=k else None
            answer=chosen[choice]['respuesta'] if choice is not None else None
        input_tokens=len(prompts[index]['prompt_token_ids']);output_tokens=row['tokens_selector_salida']
        total=input_tokens+output_tokens+sum(r['tokens_entrada']+r['tokens_salida'] for r in chosen)
        if (row['indice']!=i or row['referencia']!=reference or row['muestras']!=[r['muestra'] for r in chosen]
            or row['elegido']!=choice or row['respuesta']!=answer or row['acierto']!=(answer is not None and answer==reference)
            or row['tokens_selector_entrada']!=input_tokens or type(output_tokens) is not int
            or not 0<=output_tokens<=(256 if k==0 else 32) or row['tokens_total']!=total
            or row['stop'] not in ('stop','length') or (row['stop']=='length' and output_tokens!=(256 if k==0 else 32))):
            raise ValueError('Checkpoint de selección incoherente')

def run(llm,tok,SamplingParams,eos,samples_path,output,engine_protocol,problems=200,batch_problems=4):
    if problems<1 or problems>200 or problems%batch_problems:raise ValueError('Número de problemas incompatible')
    groups=load_samples(samples_path);path=Path(output);meta=path.with_suffix(path.suffix+'.protocol.json');parts=path.with_suffix(path.suffix+'.parts')
    protocol={'modelo':MODEL,'revision':REV,'backend':'vllm','engine':engine_protocol,
              'muestras_sha256':digest(samples_path),'codigo_sha256':digest(__file__),
              'problemas':problems,'grupo':batch_problems,
              'ks':KS,'seleccion_semilla':'1000*i+k','decodificacion':'voraz',
              'repetition_penalty':1.1,'selector_max_new':32,'voraz_max_new':256,'eos_token_ids':sorted(eos)}
    if (path.exists() or parts.exists()) and not meta.exists():raise ValueError('Archivo previo sin manifiesto')
    if meta.exists():
        if json.loads(meta.read_text(encoding='utf8'))!=protocol:raise ValueError('Protocolo distinto')
    else:atomic_write(meta,json.dumps(protocol,ensure_ascii=False,indent=2).encode('utf8'))
    parts.mkdir(exist_ok=True);old={}
    for file in sorted(parts.glob('problem-*.json')):
        suffix=file.stem.removeprefix('problem-')
        if len(suffix)!=4 or not suffix.isdigit() or not 0<=int(suffix)<problems:raise ValueError('Checkpoint inesperado')
        i=int(suffix);rows=json.loads(file.read_text(encoding='utf8'))
        check_problem(i,rows,groups[i],tok)
        old[i]=rows
    if path.exists() and len(old)!=problems:raise ValueError('Resultado final sin checkpoints completos')
    for start in range(0,problems,batch_problems):
        if all(i in old for i in range(start,start+batch_problems)):continue
        requests=[];chosen_sets=[];params=[]
        for i in range(start,start+batch_problems):
            prompts,candidates=prompts_for(i,groups[i],tok)
            requests.extend(prompts);chosen_sets.extend(candidates)
            params.extend(SamplingParams(temperature=0,top_p=1,top_k=0,repetition_penalty=1.1,
                                         max_tokens=256 if k==0 else 32,stop_token_ids=eos) for k in KS)
        outputs=llm.generate(requests,params,use_tqdm=False)
        if len(outputs)!=len(requests):raise ValueError('Faltan solicitudes')
        grouped={i:[] for i in range(start,start+batch_problems)}
        for index,result in enumerate(outputs):
            i=start+index//len(KS);k=KS[index%len(KS)];chosen=chosen_sets[index]
            if list(result.prompt_token_ids)!=requests[index]['prompt_token_ids'] or len(result.outputs)!=1:
                raise ValueError('Tokens o número de respuestas inesperados')
            item=result.outputs[0]
            if item.finish_reason not in ('stop','length'):raise ValueError('Parada inesperada')
            text=item.text;input_tokens=len(result.prompt_token_ids);output_tokens=len(item.token_ids)
            if k==0:
                answer=extract(text);chosen_index=None
            else:
                match=re.fullmatch(r'\s*(\d+)\s*[.\s]*',text)
                chosen_index=int(match.group(1))-1 if match and 1<=int(match.group(1))<=k else None
                answer=chosen[chosen_index]['respuesta'] if chosen_index is not None else None
            ref=groups[i][0]['referencia']
            grouped[i].append({'indice':i,'k':k,'respuesta':answer,'texto':text,'referencia':ref,
                               'muestras':[r['muestra'] for r in chosen],'elegido':chosen_index,
                               'acierto':answer is not None and answer==ref,
                               'tokens_total':input_tokens+output_tokens+sum(r['tokens_entrada']+r['tokens_salida'] for r in chosen),
                               'tokens_selector_entrada':input_tokens,'tokens_selector_salida':output_tokens,
                               'stop':item.finish_reason})
        for i,rows in grouped.items():
            if i in old and old[i]!=rows:raise ValueError('Lote parcial divergente; no se modifica')
        for i,rows in grouped.items():
            if i not in old:
                check_problem(i,rows,groups[i],tok)
                atomic_write(parts/f'problem-{i:04}.json',json.dumps(rows,ensure_ascii=False).encode('utf8'));old[i]=rows
        print('selector problemas',start+batch_problems,'de',problems,flush=True)
    payload=''.join(json.dumps(r,ensure_ascii=False)+'\n' for i in range(problems) for r in old[i]).encode('utf8')
    if path.exists():
        if digest(path)!=hashlib.sha256(payload).hexdigest():raise ValueError('Resultado ensamblado divergente')
    else:atomic_write(path,payload)
    print('selector completo',problems*len(KS),'filas',flush=True)
