"""ReAct autónomo para dos preguntas ya medidas; comparte un 7B cargado."""
import collections,importlib.util,json,re,string,sys
from pathlib import Path
import numpy as np
import torch
from sentence_transformers import SentenceTransformer

ROOT=Path('rag-eval')
def run(model,tok):
    spec=importlib.util.spec_from_file_location('react_engine','react_engine.py')
    engine=importlib.util.module_from_spec(spec);sys.modules[spec.name]=engine;spec.loader.exec_module(engine)
    cases=json.loads((ROOT/'hotpot.json').read_text(encoding='utf-8'))
    docs=json.loads((ROOT/'docs.json').read_text(encoding='utf-8'));titles=docs['titles'];texts=docs['texts']
    vectors=np.load(ROOT/'index.npz')['vectors'];words=[re.findall(r'\w+',x.lower()) for x in texts]
    counts=[collections.Counter(w) for w in words];df=collections.Counter(w for c in counts for w in c)
    n=len(texts);avg=np.mean([len(w) for w in words])
    encoder=SentenceTransformer('intfloat/multilingual-e5-small',revision='614241f622f53c4eeff9890bdc4f31cfecc418b3',device='cpu')
    def norm(s):
        return ' '.join(w for w in s.lower().translate(str.maketrans('','',string.punctuation)).split() if w not in ('a','an','the'))
    def encode(messages):return tok.apply_chat_template(messages,tokenize=False,add_generation_prompt=True)
    def count(messages):return int(tok(encode(messages),return_tensors='pt')['input_ids'].shape[1])
    def policy(messages,max_new):
        prompt=encode(messages);batch=tok(prompt,return_tensors='pt').to('cuda')
        with torch.no_grad():output=model.generate(**batch,max_new_tokens=max_new,do_sample=False,pad_token_id=tok.eos_token_id)
        tokens=output[0,batch['input_ids'].shape[1]:]
        return engine.PolicyResponse(tok.decode(tokens,skip_special_tokens=True).strip(),int(batch['input_ids'].shape[1]),int(len(tokens)),prompt)
    out=[]
    for case in (cases[1],cases[4]):
        found=[]
        def search(query):
            if len(found)>=4:return 'Search budget exhausted.'
            lex=np.zeros(n)
            for word in re.findall(r'\w+',query.lower()):
                if word not in df:continue
                idf=np.log(1+(n-df[word]+.5)/(df[word]+.5))
                for i,c in enumerate(counts):
                    f=c[word]
                    if f:lex[i]+=idf*f*2.2/(f+1.2*(.25+.75*len(words[i])/avg))
            query_vector=encoder.encode(['query: '+query],normalize_embeddings=True,convert_to_numpy=True)[0]
            dense=vectors@query_vector;score=np.zeros(n)
            for order in (np.argsort(-lex,kind='stable'),np.argsort(-dense,kind='stable')):
                for rank,i in enumerate(order,1):score[i]+=1/(60+rank)
            ids=[int(i) for i in np.argsort(-score,kind='stable') if int(i) not in found][:min(2,4-len(found))]
            found.extend(ids)
            return '\n'.join('['+titles[i]+'] '+' '.join(texts[i].split()[:100]) for i in ids)
        question=('Answer the question using search if needed. You may call search at most twice; each call returns up to two new passages. '
                  'You decide when to search and when to finish. Return the short answer in the final JSON. Question: '+case['question'])
        result=engine.run_agent(question,policy,{'search':search},count,max_steps=4,max_total_tokens=8192,
                                max_context_tokens=4096,max_new_tokens=96,timeout_seconds=600)
        gold=set(case['supporting_facts']['title']);answer=result['answer'] or ''
        item={'question':case['question'],'reference':case['answer'],'ids':found,'titles':[titles[i] for i in found],
              'recall':len(gold.intersection(titles[i] for i in found))/len(gold),
              'exact':norm(answer)==norm(case['answer']),'result':result}
        out.append(item);(ROOT/'react_autonomous.json').write_text(json.dumps(out,ensure_ascii=False,indent=2),encoding='utf-8')
        print('ReAct',case['question'][:40],result['stop_reason'],'passages',len(found),'recall',item['recall'],'exact',item['exact'],flush=True)

if __name__=='__main__':
    from transformers import AutoTokenizer,AutoModelForCausalLM,BitsAndBytesConfig
    name='Qwen/Qwen2.5-7B-Instruct';rev='a09a35458c702b33eeacc393d103063234e8bc28'
    tok=AutoTokenizer.from_pretrained(name,revision=rev)
    cfg=BitsAndBytesConfig(load_in_4bit=True,bnb_4bit_quant_type='nf4',bnb_4bit_compute_dtype=torch.float16)
    model=AutoModelForCausalLM.from_pretrained(name,revision=rev,quantization_config=cfg,device_map={'':0},dtype=torch.float16).eval()
    run(model,tok)
