"""10 tareas, dos usuarios simulados y dos respuestas del agente por usuario."""
import json,re,time
from pathlib import Path
import numpy as np
import torch

ROOT=Path('agent-bench');ROOT.mkdir(parents=True,exist_ok=True)
TASKS=[('preferred city','Madrid',['Madrid','Paris']),('preferred city','Oslo',['Oslo','Rome']),
       ('preferred drink','tea',['tea','coffee']),('preferred drink','water',['water','juice']),
       ('meeting day','Monday',['Monday','Friday']),('meeting day','Tuesday',['Tuesday','Thursday']),
       ('preferred color','blue',['blue','green']),('preferred color','red',['red','yellow']),
       ('delivery month','May',['May','June']),('delivery month','April',['April','July'])]
def run(model,tok):
    path=ROOT/'user_sim.json';records=json.loads(path.read_text(encoding='utf-8')) if path.exists() else []
    done={(r['task'],r['user_draw'],r['agent_draw']) for r in records}
    def generate(prompt,seed,temperature):
        chat=tok.apply_chat_template([{'role':'user','content':prompt}],tokenize=False,add_generation_prompt=True)
        batch=tok(chat,return_tensors='pt').to('cuda');torch.manual_seed(seed);start=time.perf_counter()
        with torch.no_grad():out=model.generate(**batch,max_new_tokens=48,do_sample=True,temperature=temperature,top_p=.95,pad_token_id=tok.eos_token_id)
        return {'text':tok.decode(out[0,batch['input_ids'].shape[1]:],skip_special_tokens=True).strip(),
                'input_tokens':int(batch['input_ids'].shape[1]),'output_tokens':int(out.shape[1]-batch['input_ids'].shape[1]),
                'seconds':time.perf_counter()-start}
    for i,(field,secret,options) in enumerate(TASKS):
        for u in range(2):
            existing=next((r['user'] for r in records if r['task']==i and r['user_draw']==u),None)
            user=existing or generate('Act as a simulated customer. Your private '+field+' is '+secret+
                 '. The agent asks: What is your '+field+'? Answer naturally in one short sentence; do not invent facts.',270000+i*10+u,.8)
            for a in range(2):
                if (i,u,a) in done:continue
                response=generate('The customer answered: '+user['text']+'\nIdentify the '+field+'. '
                    'Reply only FINAL: followed by one of '+', '.join(options)+'.',280000+i*20+u*2+a,.7)
                match=re.fullmatch(r'FINAL\s*:\s*([A-Za-z]+)[.!]?',response['text'],re.I)
                answer=match.group(1) if match else None
                records.append({'task':i,'field':field,'secret':secret,'options':options,'user_draw':u,'agent_draw':a,
                                'user':user,'agent':response,'answer':answer,'success':int(answer is not None and answer.lower()==secret.lower())})
                path.write_text(json.dumps(records,ensure_ascii=False,indent=2),encoding='utf-8')
                print('user simulator',i,u,a,records[-1]['success'],flush=True)
    # ANOVA anidado dentro de tarea: estima varianza entre usuarios y residual.
    per_task=[]
    for i in range(len(TASKS)):
        groups=[[r['success'] for r in records if r['task']==i and r['user_draw']==u] for u in range(2)]
        if any(len(g)!=2 for g in groups):raise ValueError('diseño incompleto')
        means=np.array([np.mean(g) for g in groups]);grand=means.mean()
        within=sum((x-np.mean(g))**2 for g in groups for x in g)/2
        between=sum(2*(m-grand)**2 for m in means)
        per_task.append((between,within))
    ms_between,ms_within=np.mean(per_task,axis=0)
    rng=np.random.default_rng(27);bootstrap=[]
    for _ in range(2000):
        sampled=rng.integers(0,len(per_task),len(per_task))
        b,w=np.mean([per_task[i] for i in sampled],axis=0);bootstrap.append((b-w)/2)
    summary={'tasks':10,'user_draws_per_task':2,'agent_draws_per_user':2,
             'success':sum(r['success'] for r in records)/len(records),
             'user_variance_unclipped':float((ms_between-ms_within)/2),'agent_residual_variance':float(ms_within),
             'user_variance_cluster_bootstrap_ci':np.quantile(bootstrap,[.025,.975]).tolist(),
             'note':'Estimación ANOVA de momentos; puede ser negativa por ruido y no identifica interacción con solo dos réplicas.'}
    (ROOT/'user_sim_summary.json').write_text(json.dumps(summary,ensure_ascii=False,indent=2),encoding='utf-8')
    print('user simulator summary',summary,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))
