"""Dos consultas SQLite con ReAct real y comprobador del valor final."""
import importlib.util,json,sqlite3,sys,tempfile
from pathlib import Path
import torch
ROOT=Path('agent-bench');ROOT.mkdir(parents=True,exist_ok=True)
def load(name,path):
 spec=importlib.util.spec_from_file_location(name,path);m=importlib.util.module_from_spec(spec);sys.modules[name]=m;spec.loader.exec_module(m);return m
def run(model,tok):
 h=load('query_harness',Path('harness.py'));engine=load('query_react',Path('react_engine.py'))
 class Environment:
  def __init__(self,task):
   self.task=task;self.temp=tempfile.TemporaryDirectory(prefix='query-bench-');self.root=Path(self.temp.name);self.queried=False;self.result={}
   db=sqlite3.connect(self.root/'state.db');db.execute('CREATE TABLE cuentas(id INTEGER PRIMARY KEY, saldo INTEGER NOT NULL)')
   db.executemany('INSERT INTO cuentas VALUES (?,?)',[(1,10+task.seed),(2,20+task.seed),(3,30+task.seed)]);db.commit();db.close()
  def close(self):self.temp.cleanup()
  def read(self,arg):raise ValueError('sin archivos')
  def write(self,arg):raise ValueError('solo lectura')
  def db(self,arg):
   if json.loads(arg)!={'op':'list'}:raise ValueError('solo consulta list')
   db=sqlite3.connect(self.root/'state.db')
   try:rows=db.execute('SELECT id,saldo FROM cuentas ORDER BY id').fetchall()
   finally:db.close()
   self.queried=True;return json.dumps(rows)
  def set_result(self,result):self.result=result
  def check(self):
   answer=self.result.get('answer') if isinstance(self.result,dict) else None
   return self.queried and str(answer).strip()==str(20+self.task.seed),'consulta real y saldo final exacto'
 path=ROOT/'query-results.json';records=json.loads(path.read_text(encoding='utf8')) if path.exists() else []
 done={r['task'] for r in records}
 for i in range(2):
  task=h.Task('query-'+str(i),'db-query','Consulta la tabla cuentas y responde solo con el saldo de la cuenta 2.',1,i)
  if task.id in done:continue
  def agent(task,tools):
   schema=('The db tool accepts exactly a JSON string {"op":"list"} and returns account ids and balances. '
           'Call db to inspect the database, then finish with the balance of account 2 as the final answer.\n')
   def serialize(messages):return tok.apply_chat_template(messages,tokenize=False,add_generation_prompt=True)
   def count(messages):return int(tok(serialize(messages),return_tensors='pt')['input_ids'].shape[1])
   def policy(messages,max_new):
    prompt=serialize(messages);batch=tok(prompt,return_tensors='pt').to('cpu')
    with torch.no_grad():out=model.generate(**batch,max_new_tokens=max_new,do_sample=True,temperature=.7,top_p=.95,pad_token_id=tok.eos_token_id)
    ni=int(batch['input_ids'].shape[1]);generated=out[0,ni:]
    return engine.PolicyResponse(tok.decode(generated,skip_special_tokens=True).strip(),ni,int(len(generated)),prompt)
   torch.manual_seed(271000+i)
   return engine.run_agent(schema+task.instruction,policy,tools,count,max_steps=6,max_total_tokens=5000,max_context_tokens=2048,max_new_tokens=128,timeout_seconds=600)
  result=h.run(task,agent,environment_factory=Environment);records.append(result)
  path.write_text(json.dumps(records,ensure_ascii=False,indent=2),encoding='utf8')
  print('Consulta SQLite',task.id,result['success'],flush=True)
 print('Consultas con ReAct:',sum(x['success'] is True for x in records),'/',len(records),flush=True)

if __name__=='__main__':
 import torch
 from huggingface_hub import hf_hub_download
 from transformers import AutoTokenizer
 from llama_cpp import Llama
 from cpu_adapter import ModelAdapter,TokenizerAdapter
 repo='Qwen/Qwen2.5-7B-Instruct-GGUF';rev='bb5d59e06d9551d752d08b292a50eb208b07ab1f'
 names=['qwen2.5-7b-instruct-q4_k_m-00001-of-00002.gguf','qwen2.5-7b-instruct-q4_k_m-00002-of-00002.gguf']
 paths=[hf_hub_download(repo,name,revision=rev) for name in names]
 model=Llama(model_path=paths[0],n_ctx=2048,n_threads=8,n_batch=512,n_gpu_layers=0,verbose=False)
 tok=AutoTokenizer.from_pretrained('Qwen/Qwen2.5-7B-Instruct',revision='a09a35458c702b33eeacc393d103063234e8bc28')
 torch.cuda.synchronize=lambda:None
 run(ModelAdapter(model),TokenizerAdapter(tok,model))
