"""Genera propuestas de Game 24 con Qwen 1.5B y verifica cada operación."""
import argparse
from fractions import Fraction
import hashlib
from itertools import combinations
import json
from pathlib import Path
import re
import torch
import transformers
from transformers import AutoModelForCausalLM,AutoTokenizer

REV='989aa7980e4cf806f80c7fef2b1adb7bc71aa306'
WEIGHTS_SHA256='dd924a11b4c220f385b51ffa522daea7c9f3d850e31b162bb5661df483c6d3ee'
CASES=[[4,9,10,13],[1,3,4,6],[3,3,8,8],[2,2,6,6]]

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

def operations(values):
    for i,j in combinations(range(len(values)),2):
        a,b=values[i],values[j]; rest=[v for k,v in enumerate(values) if k not in (i,j)]
        vals=[a+b,a-b,b-a,a*b]
        if b: vals.append(a/b)
        if a: vals.append(b/a)
        for x in vals: yield rest+[x]

def viable(values):
    if len(values)==1: return values[0]==24
    return any(viable(nxt) for nxt in operations(values))

def parse_proposals(text,values):
    # Una acción se acepta solo si usa dos ocurrencias disponibles y la igualdad es exacta.
    number=r'[-+]?\d+(?:/\d+)?'
    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=Fraction(match.group(1)); b=Fraction(match.group(3)); stated=Fraction(match.group(4))
            remaining=list(values); remaining.remove(a); remaining.remove(b)
            op=match.group(2)
            calculated={'+':lambda:a+b,'-':lambda:a-b,'*':lambda:a*b,'/':lambda:a/b}[op]()
            if calculated!=stated: continue
            child=remaining+[calculated]; key=tuple(sorted(child))
            if key in seen: continue
            seen.add(key)
            result.append({'operation':f'{a} {op} {b} = {calculated}',
                           'remaining':[str(x) for x in child],
                           'solvable':viable(child)})
        except (ValueError,ZeroDivisionError): continue
    return result

def main():
    ap=argparse.ArgumentParser(); ap.add_argument('--model-path',required=True)
    ap.add_argument('--output',required=True); ap.add_argument('--max-tokens',type=int,default=256)
    args=ap.parse_args()
    model_path=Path(args.model_path)
    if model_path.name!=REV: ap.error('Revisión incorrecta del modelo')
    if not torch.cuda.is_available(): raise RuntimeError('Se requiere CUDA')
    out=Path(args.output); out.mkdir(parents=True,exist_ok=True)
    sha=digest(model_path/'model.safetensors')
    if sha!=WEIGHTS_SHA256:raise ValueError('El hash de los pesos no coincide con la revisión fijada')
    protocol={'revision':REV,'model_sha256':sha,'cases':CASES,'max_tokens':args.max_tokens,
              'temperature':.8,'top_p':.9,'seed_rule':'470000 + case*10000 + node',
              'judge_seed_rule':'570000 + case*10000 + node',
              'torch_version':str(torch.__version__),'transformers_version':transformers.__version__,
              'device':torch.cuda.get_device_name(),'dtype':'bfloat16','backend':'transformers',
              'config_sha256':{name:digest(model_path/name) for name in ('config.json','tokenizer.json','tokenizer_config.json','generation_config.json')},
              'code_sha256':digest(__file__)}
    proto=out/'protocol.json'
    if proto.exists() and json.loads(proto.read_text(encoding='utf8'))!=protocol:
        raise ValueError('La campaña previa tiene otro protocolo')
    if not proto.exists():
        tmp=proto.with_suffix('.tmp');tmp.write_text(json.dumps(protocol,indent=2),encoding='utf8');tmp.replace(proto)
    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()
    for case_id,case in enumerate(CASES):
        # Se exploran como máximo cinco propuestas de cada estado hasta profundidad 2.
        queue=[{'values':[str(x) for x in case],'depth':0,'path':[]}]
        nodes=[]
        while queue:
            node=queue.pop(0); idx=len(nodes)
            file=out/f'c{case_id}-n{idx:03d}.json'
            if file.exists():
                record=json.loads(file.read_text(encoding='utf8'))
                if record['values']!=node['values'] or record['path']!=node['path']:
                    raise ValueError('Checkpoint de nodo incompatible')
            else:
                values=[Fraction(x) for x in node['values']]
                prompt=('Game of 24. Available numbers: '+', '.join(map(str,values))+'. '
                        'Propose up to eight different legal next operations, using two available numbers once each. '
                        'Use only +, -, * or /. Write one equation per line, for example 4 + 9 = 13. '
                        'Each line must contain exactly two operands and one operator; never chain operations. '
                        'Do not invent or reuse numbers. Do not solve the whole puzzle yet.')
                messages=[{'role':'user','content':prompt}]
                encoded=tok.apply_chat_template(messages,add_generation_prompt=True,tokenize=True,
                                                return_tensors='pt',return_dict=True).to('cuda')
                torch.manual_seed(470000+case_id*10000+idx)
                with torch.inference_mode():
                    generated=model.generate(**encoded,do_sample=True,temperature=.8,top_p=.9,top_k=0,
                                             max_new_tokens=args.max_tokens,pad_token_id=tok.eos_token_id)
                tail=generated[0,encoded['input_ids'].shape[1]:]
                text=tok.decode(tail,skip_special_tokens=True)
                parsed=parse_proposals(text,values)
                judge_text=''; judge_input=judge_output=0;judge_token_ids=[]
                if parsed:
                    listed='\n'.join(f"{i+1}: {', '.join(p['remaining'])}" for i,p in enumerate(parsed[:5]))
                    query=('For each list of remaining numbers, judge whether 24 can still be made using '
                           'each number once with +, -, * and /. Reply one line per list as '
                           '"number: sure", "number: likely" or "number: impossible".\n'+listed)
                    judged=tok.apply_chat_template([{'role':'user','content':query}],add_generation_prompt=True,
                                                   tokenize=True,return_tensors='pt',return_dict=True).to('cuda')
                    torch.manual_seed(570000+case_id*10000+idx)
                    with torch.inference_mode():
                        answer=model.generate(**judged,do_sample=True,temperature=.8,top_p=.9,top_k=0,
                                              max_new_tokens=args.max_tokens,pad_token_id=tok.eos_token_id)
                    judge_tail=answer[0,judged['input_ids'].shape[1]:]
                    judge_token_ids=judge_tail.tolist()
                    judge_text=tok.decode(judge_tail,skip_special_tokens=True)
                    judge_input=int(judged['attention_mask'].sum()); judge_output=len(judge_tail)
                    ratings={int(n):label.lower() for n,label in re.findall(r'(?im)^\s*(\d+)\s*[:.)-]\s*(sure|likely|impossible)\b',judge_text)}
                    for i,proposal in enumerate(parsed): proposal['judge']=ratings.get(i+1,'unknown')
                record={**node,'text':text,'proposals':parsed,
                        'input_tokens':int(encoded['attention_mask'].sum()),'output_tokens':len(tail),
                        'output_token_ids':tail.tolist(),'judge_text':judge_text,'judge_input_tokens':judge_input,
                        'judge_output_tokens':judge_output,'judge_token_ids':judge_token_ids}
                tmp=file.with_suffix('.tmp'); tmp.write_text(json.dumps(record,ensure_ascii=False),encoding='utf8'); tmp.replace(file)
            nodes.append(record)
            if node['depth']<2:
                for proposal in record['proposals'][:5]:
                    queue.append({'values':proposal['remaining'],'depth':node['depth']+1,
                                  'path':node['path']+[proposal['operation']]})
            print('caso',case_id,'nodo',idx,'profundidad',node['depth'],
                  'propuestas válidas',len(record['proposals']),flush=True)
        target=out/f'case{case_id}.json'; target.write_text(json.dumps(nodes,ensure_ascii=False,indent=2),encoding='utf8')
        print('caso',case_id,'nodos',len(nodes),'sha256',hashlib.sha256(target.read_bytes()).hexdigest(),flush=True)

if __name__=='__main__': main()
