"""Best-of-N, haz y PUCT en Countdown con Qwen 1.5B y costes de tokens.

Cada llamada cobra entrada y salida tanto del proponente como del evaluador.
Una llamada nunca supera el presupuesto restante, aunque puede truncarse. Se
guardan los textos y acciones legales; un fallo de formato no es un acierto.
"""
import argparse
from fractions import Fraction
import hashlib
import json
import math
from pathlib import Path
import re
import time
import torch
import torch.nn.functional as F
import transformers
from transformers import AutoModelForCausalLM,AutoTokenizer
import countdown

REV='989aa7980e4cf806f80c7fef2b1adb7bc71aa306'
WEIGHTS_SHA256='dd924a11b4c220f385b51ffa522daea7c9f3d850e31b162bb5661df483c6d3ee'

def job_seed(problem,budget_index,method_index,split='test'):
    # Cada trabajo tiene un bloque exclusivo de 8192 semillas. Como cada
    # llamada consume al menos un token y el tope es 4096, no se solapan.
    return 730000+8192*(9*problem+3*budget_index+method_index+(900 if split=='train' else 0))

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 operations(text,state):
    number=r'[-+]?\d+(?:/\d+)?'
    # Acepta una igualdad completa por línea, con viñeta o delimitador
    # matemático opcional. Nunca extrae una subexpresión de una cadena.
    pattern=re.compile(r'^\s*(?:[-*•]\s+|\d+[.)]\s+)?'
                       r'(?:\\\(|\\\[|\$)?\s*'
                       r'('+number+r')\s*([+*/-])\s*('+number+r')\s*=\s*('+number+r')'
                       r'\s*(?:\\\)|\\\]|\$)?\s*$')
    result=[];seen=set()
    for line in text.splitlines():
        match=pattern.fullmatch(line)
        if match is None:continue
        try:
            a,b,claimed=Fraction(match[1]),Fraction(match[3]),Fraction(match[4]);rest=list(state)
            i=next(i for i,x in enumerate(rest) if x[0]==a);left=rest.pop(i)
            i=next(i for i,x in enumerate(rest) if x[0]==b);right=rest.pop(i)
            op=match[2];value={'+':lambda:a+b,'-':lambda:a-b,'*':lambda:a*b,'/':lambda:a/b}[op]()
            if value!=claimed:continue
            child=rest+[(value,f'({left[1]}{op}{right[1]})')];key=tuple(sorted(x[0] for x in child))
            if key in seen:continue
            operation=f'{match[1]} {op} {match[3]} = {match[4]}'
            seen.add(key);result.append((child,operation))
        except (ValueError,ZeroDivisionError,StopIteration):continue
    return result[:4]

class Budget:
    def __init__(self,model,tok,amount,seed):
        self.model=model;self.tok=tok;self.limit=amount;self.spent=0
        self.seed_base=seed;self.generated_calls=0;self.calls=[]
        self.device=next(model.parameters()).device
        eos=model.generation_config.eos_token_id
        self.eos=set(eos if isinstance(eos,list) else [eos]) | {tok.eos_token_id}
    def call(self,kind,prompt):
        enc=self.tok.apply_chat_template([{'role':'user','content':prompt}],tokenize=True,
            add_generation_prompt=True,return_tensors='pt',return_dict=True).to(self.device)
        n=int(enc['attention_mask'].sum());available=self.limit-self.spent-n
        if available<1:return None
        cap=min(128,available);seed=self.seed_base+self.generated_calls
        self.generated_calls+=1;torch.manual_seed(seed)
        if self.device.type=='cuda':torch.cuda.synchronize(self.device)
        started=time.perf_counter()
        with torch.inference_mode():
            output=self.model.generate(**enc,do_sample=True,temperature=.8,top_p=.9,top_k=0,
                repetition_penalty=1.1,max_new_tokens=cap,pad_token_id=self.tok.eos_token_id)
        if self.device.type=='cuda':torch.cuda.synchronize(self.device)
        elapsed=time.perf_counter()-started
        tokens=output[0,enc['input_ids'].shape[1]:].tolist();stop=next((i for i,x in enumerate(tokens) if x in self.eos),None)
        if stop is not None:tokens=tokens[:stop+1]
        text=self.tok.decode(tokens,skip_special_tokens=True);self.spent+=n+len(tokens)
        self.calls.append({'kind':kind,'input':n,'output':len(tokens),'seed':seed,'prompt':prompt,
                           'output_token_ids':tokens,'text':text,'seconds':elapsed,
                           'truncated':stop is None and len(tokens)>=cap})
        assert self.spent<=self.limit
        return text

    def log_prior(self,prompt,operation):
        """Media de log p(token|prefijo), cobrada también como tokens procesados.

        Cada operación se puntúa como primera línea del mismo prompt, no en el
        contexto de las otras propuestas. El softmax posterior normaliza solo
        sobre las operaciones válidas que se llegaron a puntuar.
        """
        enc=self.tok.apply_chat_template([{'role':'user','content':prompt}],tokenize=True,
            add_generation_prompt=True,return_tensors='pt',return_dict=True).to(self.device)
        ids=self.tok(operation,add_special_tokens=False,return_tensors='pt')['input_ids'].to(self.device)
        n=enc['input_ids'].shape[1]; k=ids.shape[1]
        cost=n+k
        if k==0 or self.spent+cost>self.limit:return None
        full=torch.cat((enc['input_ids'],ids),dim=1)
        if self.device.type=='cuda':torch.cuda.synchronize(self.device)
        started=time.perf_counter()
        with torch.inference_mode():
            # Solo se proyectan los k+1 últimos estados; las k primeras filas
            # predicen los tokens de la operación. No se necesita caché KV.
            logits=self.model(input_ids=full,attention_mask=torch.ones_like(full),
                              use_cache=False,logits_to_keep=k+1).logits
            picked=F.log_softmax(logits[0,:k].float(),dim=-1)
            value=float(picked.gather(-1,ids[0,:,None]).mean().item())
        elapsed=time.perf_counter()-started
        if not math.isfinite(value):raise ValueError('Prior no finito')
        self.spent+=cost
        self.calls.append({'kind':'prior','input':cost,'output':0,'prompt':prompt,'text':operation,
                           'prompt_tokens':n,'candidate_tokens':k,'candidate_token_ids':ids[0].tolist(),
                           'mean_logprob':value,'seconds':elapsed})
        assert self.spent<=self.limit
        return value

    def prior_cost(self,prompt,operation):
        enc=self.tok.apply_chat_template([{'role':'user','content':prompt}],tokenize=True,
            add_generation_prompt=True,return_tensors='pt',return_dict=True)
        ids=self.tok(operation,add_special_tokens=False,return_tensors='pt')['input_ids']
        return int(enc['input_ids'].shape[1]+ids.shape[1])

    def evaluation_upper_cost(self,state,target):
        enc=self.tok.apply_chat_template([{'role':'user','content':score_prompt(state,target)}],
            tokenize=True,add_generation_prompt=True,return_tensors='pt',return_dict=True)
        return int(enc['input_ids'].shape[1])+128

    def log_priors_batched(self,prompt,operations):
        """Evalúa candidatos juntos; el presupuesto lógico cuenta cada prompt completo."""
        enc=self.tok.apply_chat_template([{'role':'user','content':prompt}],tokenize=True,
            add_generation_prompt=True,return_tensors='pt',return_dict=True)
        prefix=enc['input_ids'][0]
        candidates=[self.tok(x,add_special_tokens=False,return_tensors='pt')['input_ids'][0] for x in operations]
        if not candidates or any(len(x)==0 for x in candidates):raise ValueError('Candidata vacía')
        n=len(prefix);lengths=[len(x) for x in candidates];costs=[n+k for k in lengths]
        if self.spent+sum(costs)>self.limit:raise ValueError('Lote excede presupuesto')
        seqs=[torch.cat((prefix,ids)) for ids in candidates]
        full=torch.nn.utils.rnn.pad_sequence(seqs,batch_first=True,padding_value=self.tok.eos_token_id).to(self.device)
        mask=(torch.arange(full.shape[1],device=self.device)[None,:] <
              torch.tensor(costs,device=self.device)[:,None]).long()
        if self.device.type=='cuda':torch.cuda.synchronize(self.device)
        started=time.perf_counter()
        with torch.inference_mode():
            hidden=self.model.model(input_ids=full,attention_mask=mask,use_cache=False).last_hidden_state
            positions=[hidden[i,n-1:n-1+k] for i,k in enumerate(lengths)]
            logits=self.model.lm_head(torch.cat(positions,dim=0)).float()
            target=torch.cat(candidates).to(self.device)
            token_logps=F.log_softmax(logits,dim=-1).gather(-1,target[:,None]).squeeze(-1)
            values=[float(x.mean().item()) for x in token_logps.split(lengths)]
        if self.device.type=='cuda':torch.cuda.synchronize(self.device)
        elapsed=time.perf_counter()-started
        if not all(math.isfinite(x) for x in values):raise ValueError('Prior no finito')
        for operation,ids,k,cost,value in zip(operations,candidates,lengths,costs,values):
            self.spent+=cost
            self.calls.append({'kind':'prior','input':cost,'output':0,'prompt':prompt,'text':operation,
                'prompt_tokens':n,'candidate_tokens':k,'candidate_token_ids':ids.tolist(),
                'mean_logprob':value,'seconds':elapsed/len(candidates),
                'shared_batch_seconds':elapsed,'batch_size':len(candidates),
                'batch_padded_tokens':int(full.numel()),'batch_real_tokens':sum(costs)})
        return values

def score_prompt(state,target):
    return ('Rate from 0 to 10 how promising these remaining numbers are for reaching '+str(target)+
            ' using each exactly once and operations +, -, *, /. Reply only with the integer. Numbers: '+
            ', '.join(str(x[0]) for x in state))
def score(budget,state,target):
    text=budget.call('evaluador',score_prompt(state,target))
    if text is None:return None
    match=re.fullmatch(r'\s*(10|[0-9])\s*[.]?\s*',text)
    return int(match[1])/10 if match else 0.

def proposal_prompt(state,target):
    return ('Available numbers: '+', '.join(str(x[0]) for x in state)+'. Target: '+str(target)+'. '
            'Propose up to four different legal next arithmetic operations. Use only two available numbers and +, -, * or /. '
            'One complete equality per line, exactly two operands and one operator; '
            'never chain operations or invent numbers. Example: 4 + 9 = 13. Do not solve the entire problem.')
def expand(budget,state,target,use_prior=False):
    prompt=proposal_prompt(state,target)
    text=budget.call('proponente',prompt)
    if text is None:return []
    children=[]
    pending=operations(text,state)
    while pending:
        # Agrupa solo si caben todos los priors y el peor caso de 128 tokens
        # para cada evaluación. Así ninguna llamada posterior queda excluida
        # por reservar el lote: mismos candidatos que en el orden secuencial.
        group=[]
        if use_prior and hasattr(budget,'log_priors_batched'):
            total=0
            for state2,operation in pending:
                cost=budget.prior_cost(prompt,operation)
                if len(state2)>1:cost+=budget.evaluation_upper_cost(state2,target)
                if budget.spent+total+cost>budget.limit:break
                group.append((state2,operation));total+=cost
        if len(group)>=2:
            priors=budget.log_priors_batched(prompt,[x[1] for x in group])
        else:
            group=[pending[0]]
            one=budget.log_prior(prompt,group[0][1]) if use_prior else None
            if use_prior and one is None:break
            priors=[one]
        for (state2,operation),log_prior in zip(group,priors):
            if len(state2)==1:value=float(state2[0][0]==target)
            else:
                value=score(budget,state2,target)
                if value is None:break
            children.append({'state':state2,'operation':operation,'value':value,'log_prior':log_prior})
        else:
            pending=pending[len(group):]
            continue
        break
    if use_prior and children:
        # Normalización solo entre propuestas puntuadas; no es una distribución
        # sobre todas las operaciones legales posibles.
        weights=[math.exp(c['log_prior']-max(x['log_prior'] for x in children)) for c in children]
        total=sum(weights)
        for child,weight in zip(children,weights):child['prior']=weight/total
    return children

def solve(task,method,budget):
    start=[(Fraction(n),str(n)) for n in task['numbers']];target=task['target']
    if method=='bon':
        while True:
            prompt=('Use each number exactly once with +, -, * or / to reach the target. '
                    'You may reason first. Put the final arithmetic expression inside <answer>...</answer>. '
                    'Numbers: '+', '.join(map(str,task['numbers']))+'. Target: '+str(target)+'.')
            text=budget.call('solucion',prompt)
            if text is None:break
            matches=re.findall(r'<answer>\s*(.*?)\s*</answer>',text,re.S)
            if matches and countdown.evaluate_expression(matches[-1],task['numbers'])==target:
                return {'solved':True,'expression':matches[-1]}
        return {'solved':False,'expression':None}
    if method=='beam':
        frontier=[{'state':start,'value':0.}]
        while frontier:
            children=[]
            for node in frontier:children.extend(expand(budget,node['state'],target))
            for child in children:
                if len(child['state'])==1 and child['state'][0][0]==target:return {'solved':True,'expression':child['state'][0][1]}
            frontier=sorted((c for c in children if len(c['state'])>1),key=lambda c:-c['value'])[:3]
        return {'solved':False,'expression':None}
    root={'state':start,'children':None,'visits':0,'sum':0.,'prior':1.,'exhausted':False}
    while budget.spent<budget.limit:
        node=root;path=[root]
        while node['children'] is not None:
            available=[x for x in node['children'] if not x['exhausted']]
            if not available:node['exhausted']=True;break
            node=max(available,key=lambda x:(x['sum']/x['visits'] if x['visits'] else x['value'])+x['prior']*math.sqrt(max(1,node['visits']))/(1+x['visits']))
            path.append(node)
        if node['exhausted']:
            for item in reversed(path):
                if item['children'] is not None and all(c['exhausted'] for c in item['children']):item['exhausted']=True
            if root['exhausted']:break
            continue
        if len(node['state'])==1:
            value=float(node['state'][0][0]==target)
            if value:return {'solved':True,'expression':node['state'][0][1]}
            node['exhausted']=True
        else:
            before=budget.spent;children=expand(budget,node['state'],target,use_prior=True)
            if not children and budget.spent==before:break
            node['children']=[{'state':x['state'],'children':None,'visits':0,'sum':0.,'prior':x['prior'],'value':x['value'],'exhausted':False} for x in children]
            if not node['children']:
                node['exhausted']=True;value=0.
            else:
                solved=next((x for x in node['children'] if len(x['state'])==1 and x['state'][0][0]==target),None)
                if solved:return {'solved':True,'expression':solved['state'][0][1]}
                # Las valoraciones ya pagadas participan también en la primera
                # selección: no se descartan todas salvo la primera propuesta.
                parent=node
                node=max(parent['children'],key=lambda x:x['value']+x['prior']*math.sqrt(max(1,parent['visits'])))
                path.append(node);value=node['value']
                if len(node['state'])==1:node['exhausted']=True
        for item in path:item['visits']+=1;item['sum']+=value
        for item in reversed(path):
            if item['children'] is not None and all(c['exhausted'] for c in item['children']):item['exhausted']=True
        if root['exhausted']:break
    return {'solved':False,'expression':None}

def validate_saved(row,task,limit,method):
    if (row.get('task')!=task or row.get('budget')!=limit or row.get('method')!=method
        or not isinstance(row.get('calls'),list) or type(row.get('solved')) is not bool):
        raise ValueError('Registro previo incompatible')
    calls=row['calls']
    if any(c.get('kind') not in ('solucion','proponente','evaluador','prior')
           or type(c.get('input')) is not int or c['input']<0
           or type(c.get('output')) is not int or c['output']<0
           or not isinstance(c.get('seconds'),(int,float)) or not math.isfinite(c['seconds'])
           or c['seconds']<0 for c in calls):
        raise ValueError('Registro de llamada inválido')
    for c in calls:
        if c['kind']=='prior':
            if (not isinstance(c.get('candidate_token_ids'),list)
                or len(c['candidate_token_ids'])!=c.get('candidate_tokens')
                or c.get('prompt_tokens',-1)+c['candidate_tokens']!=c['input']):
                raise ValueError('Tokens del prior incompatibles')
        elif (not isinstance(c.get('output_token_ids'),list)
              or len(c['output_token_ids'])!=c['output'] or type(c.get('seed')) is not int):
            raise ValueError('Tokens o semilla generados incompatibles')
    spent=sum(c['input']+c['output'] for c in calls)
    if spent!=row.get('tokens_spent') or spent>limit:
        raise ValueError('Contabilidad previa incompatible')
    if row['solved'] and (not isinstance(row.get('expression'),str)
                          or countdown.evaluate_expression(row['expression'],task['numbers'])!=task['target']):
        raise ValueError('Solución previa inválida')

def prior_trace_control(model,tok,trace,expected_weights):
    """Control de desarrollo: propuesta real previa, no resultado de test."""
    path=Path(trace)
    record=json.loads(path.read_text(encoding='utf8'))
    previous=json.loads((path.parent/'protocol.json').read_text(encoding='utf8'))
    if previous['weights_sha256']!=expected_weights or previous['split']!='train':
        raise ValueError('La traza no corresponde al modelo y partición de desarrollo')
    task=countdown.make_tasks(300,200)[0][0]
    validate_saved(record,task,1024,'beam')
    proposal=next((x for x in record['calls'] if x['kind']=='proponente'),None)
    if proposal is None:raise ValueError('No hay propuesta registrada')
    state=[(Fraction(n),str(n)) for n in task['numbers']]
    children=operations(proposal['text'],state)
    if len(children)<2:raise ValueError('La traza no contiene dos propuestas binarias completas')
    prompt=proposal_prompt(state,task['target'])
    # Las dos ramas son diagnósticos separados; cada una contabiliza el
    # coste de la propuesta original. No se incluyen en los 100 resultados.
    seq=Budget(model,tok,4096,31000000)
    bat=Budget(model,tok,4096,31010000)
    for budget in (seq,bat):
        budget.spent=proposal['input']+proposal['output']
        budget.calls.append(dict(proposal))
    seq_values=[seq.log_prior(prompt,op) for _,op in children]
    batch_values=bat.log_priors_batched(prompt,[op for _,op in children])
    values=[score(bat,child,task['target']) for child,_ in children if len(child)>1]
    if any(x is None for x in seq_values+batch_values+values):raise ValueError('Presupuesto diagnóstico insuficiente')
    return {'scope':'traza train reutilizada, control técnico, no resultado de búsqueda ni test',
            'source_sha256':digest(path),'source_protocol_sha256':digest(path.parent/'protocol.json'),
            'task':task,'operations':[op for _,op in children], 'prior_sequential':seq_values,
            'prior_batched':batch_values,'max_abs_difference':max(abs(a-b) for a,b in zip(seq_values,batch_values)),
            'model_values':values,'sequential_cost':seq.spent,'batched_cost':bat.spent,
            'sequential_calls':seq.calls,'batched_calls':bat.calls}

def main():
    ap=argparse.ArgumentParser();ap.add_argument('--model-path',required=True);ap.add_argument('--output',required=True)
    ap.add_argument('--count',type=int,default=100)
    ap.add_argument('--split',choices=['train','test'],default='test',
                    help='train solo para comprobación; la campaña final usa test reservado')
    ap.add_argument('--smoke-one-budget',action='store_true',
                    help='solo en train: comprobar el límite 1024 sin sustituir el barrido final')
    ap.add_argument('--prior-check-trace',
                    help='traza de desarrollo previa para validar prior y evaluador en esta misma carga')
    args=ap.parse_args();base=Path(args.model_path)
    if base.name!=REV or not 1<=args.count<=100:ap.error('Revisión o cantidad inválida')
    if args.smoke_one_budget and args.split!='train':ap.error('El smoke es exclusivo de train')
    if not torch.cuda.is_available():raise RuntimeError('Se requiere CUDA')
    train,test=countdown.make_tasks(300,200);tasks=(train if args.split=='train' else test)[:args.count]
    out=Path(args.output);out.mkdir(parents=True,exist_ok=True)
    weights_sha256=digest(base/'model.safetensors')
    if weights_sha256!=WEIGHTS_SHA256:raise ValueError('El hash de los pesos no coincide con la revisión fijada')
    protocol={'revision':REV,'weights_sha256':weights_sha256,
              'config_sha256':{name:digest(base/name) for name in ('config.json','tokenizer.json','tokenizer_config.json','generation_config.json')},
              'tasks_sha256':digest(countdown.__file__),
              'code_sha256':digest(__file__),'split':args.split,'count':args.count,
              'budgets':[1024] if args.smoke_one_budget else [1024,2048,4096],
              'methods':['bon','beam','mcts'],
              'seed_rule':'730000 + 8192*(9*problem + 3*budget_index + method_index + 900*es_train) + indice_de_llamada_generativa',
              'torch_version':str(torch.__version__),'transformers_version':transformers.__version__,
              'device':torch.cuda.get_device_name(),'dtype':'bfloat16','backend':'transformers',
              'tokens':'entrada y salida generadas más entrada y tokens candidatos puntuados del prior, sin atribuir ahorro de caché',
              'prior':'log-probabilidad media teacher-forced con logits originales, sin temperatura/top-p; softmax entre propuestas puntuadas',
              'proposal_format':'una igualdad binaria completa por línea; operaciones encadenadas se rechazan',
              'seconds':'tiempo de pared CUDA sincronizada; lotes de prior reparten tiempo común entre candidatos; puede incluir contención',
              'prior_batch':'agrupa candidatos solo cuando caben todos los priors y el máximo de sus evaluaciones; padding a derecha y mismas entradas'}
    meta=out/'protocol.json'
    if meta.exists() and json.loads(meta.read_text(encoding='utf8'))!=protocol:raise ValueError('Protocolo diferente')
    if not meta.exists():
        tmp=meta.with_suffix('.tmp');tmp.write_text(json.dumps(protocol,ensure_ascii=False,indent=2),encoding='utf8');tmp.replace(meta)
    tok=AutoTokenizer.from_pretrained(base,local_files_only=True);tok.pad_token=tok.eos_token
    model=AutoModelForCausalLM.from_pretrained(base,dtype=torch.bfloat16,local_files_only=True).to('cuda').eval()
    if args.prior_check_trace:
        preflight=out/'preflight-train.json'
        if preflight.exists():
            checked=json.loads(preflight.read_text(encoding='utf8'))
            trace=Path(args.prior_check_trace)
            if (checked['source_sha256']!=digest(trace)
                or checked['source_protocol_sha256']!=digest(trace.parent/'protocol.json')):
                raise ValueError('El control previo corresponde a otra traza')
        else:
            checked=prior_trace_control(model,tok,args.prior_check_trace,weights_sha256)
            tmp=preflight.with_suffix('.tmp');tmp.write_text(json.dumps(checked,ensure_ascii=False,indent=2),encoding='utf8');tmp.replace(preflight)
        print('control train: prior, lote y evaluador registrados; diferencia máxima',
              checked['max_abs_difference'],flush=True)
    for i,task in enumerate(tasks):
        for bidx,limit in enumerate(protocol['budgets']):
            for midx,method in enumerate(protocol['methods']):
                file=out/f'p{i:04d}-b{limit}-{method}.json'
                if file.exists():
                    validate_saved(json.loads(file.read_text(encoding='utf8')),task,limit,method)
                    continue
                budget=Budget(model,tok,limit,job_seed(i,bidx,midx,args.split))
                result=solve(task,method,budget)
                if result['solved'] and countdown.evaluate_expression(result['expression'],task['numbers'])!=task['target']:
                    raise ValueError('Una solución no pasó la verificación exacta')
                payload={'task':task,'budget':limit,'method':method,'tokens_spent':budget.spent,'calls':budget.calls,**result}
                tmp=file.with_suffix('.tmp');tmp.write_text(json.dumps(payload,ensure_ascii=False),encoding='utf8');tmp.replace(file)
                print('problema',i,method,limit,'gastados',budget.spent,'éxito',result['solved'],flush=True)

if __name__=='__main__':main()
