"""Cruza dos simuladores y dos temperaturas sobre las mismas 10 tareas."""
import importlib.util,json,re,sys,time
from pathlib import Path
import numpy as np
import torch
from huggingface_hub import hf_hub_download
from llama_cpp import Llama
from transformers import AutoTokenizer
ROOT=Path('agent-bench');ROOT.mkdir(parents=True,exist_ok=True)
def run(model,tok):
    spec=importlib.util.spec_from_file_location('sim_tasks',Path('user-sim-cpu.py'))
    sim=importlib.util.module_from_spec(spec);sys.modules[spec.name]=sim;spec.loader.exec_module(sim)
    path=ROOT/'user_sim_compare.json';records=json.loads(path.read_text(encoding='utf8')) if path.exists() else []
    done={(r['simulator'],r['temperature'],r['task'],r['user_draw'],r['agent_draw']) for r in records}
    model_path=hf_hub_download('Qwen/Qwen2.5-0.5B-Instruct-GGUF','qwen2.5-0.5b-instruct-q4_k_m.gguf',revision='9217f5db79a29953eb74d5343926648285ec7e67')
    small=Llama(model_path=model_path,n_ctx=2048,n_threads=4,verbose=False)
    small_tok=AutoTokenizer.from_pretrained('Qwen/Qwen2.5-0.5B-Instruct',revision='7ae557604adf67be50417f59c2c2f167def9a775')
    def user_generate(prompt,seed,temperature,which):
        if which=='0.5B':
            chat=small_tok.apply_chat_template([{'role':'user','content':prompt}],tokenize=False,add_generation_prompt=True)
            small.reset();small.set_seed(seed);start=time.perf_counter()
            result=small.create_completion(prompt=chat,max_tokens=48,temperature=temperature,top_p=.95)
            return {'text':result['choices'][0]['text'].strip(),'input_tokens':result['usage']['prompt_tokens'],
                    'output_tokens':result['usage']['completion_tokens'],'seconds':time.perf_counter()-start}
        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}
    def agent_generate(prompt,seed):
        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=.7,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 which,temp in (('7B',.2),('0.5B',.2),('0.5B',.8)):
        for i,(field,secret,options) in enumerate(sim.TASKS):
            for u in range(2):
                previous=next((r['user'] for r in records if r['simulator']==which and r['temperature']==temp and r['task']==i and r['user_draw']==u),None)
                prompt='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.'
                user=previous or user_generate(prompt,270000+i*10+u,temp,which)
                for a in range(2):
                    if (which,temp,i,u,a) in done:continue
                    request='The customer answered: '+user['text']+'\nIdentify the '+field+'. Reply only FINAL: followed by one of '+', '.join(options)+'.'
                    agent=agent_generate(request,280000+i*20+u*2+a)
                    match=re.fullmatch(r'FINAL\s*:\s*([A-Za-z]+)[.!]?',agent['text'],re.I);answer=match.group(1) if match else None
                    records.append({'simulator':which,'temperature':temp,'task':i,'field':field,'secret':secret,'options':options,
                        'user_draw':u,'agent_draw':a,'user':user,'agent':agent,'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='utf8')
                    print('sim compare',which,temp,i,u,a,records[-1]['success'],flush=True)
    original=json.loads((ROOT/'user_sim.json').read_text(encoding='utf8'))
    all_rows=records+[{**r,'simulator':'7B','temperature':.8} for r in original]
    summary={}
    for which,temp in (('7B',.8),('7B',.2),('0.5B',.2),('0.5B',.8)):
        subset=[r for r in all_rows if r['simulator']==which and r['temperature']==temp];assert len(subset)==40
        per=[]
        for i in range(10):
            groups=[[r['success'] for r in subset if r['task']==i and r['user_draw']==u] for u in range(2)]
            assert all(len(g)==2 for g in groups)
            means=np.array([np.mean(g) for g in groups]);grand=means.mean()
            per.append((sum(2*(m-grand)**2 for m in means),sum((x-np.mean(g))**2 for g in groups for x in g)/2))
        b,w=np.mean(per,axis=0);summary[which+'-'+str(temp)]={'n':len(subset),'success':sum(r['success'] for r in subset)/len(subset),
            'user_variance_unclipped':float((b-w)/2),'agent_residual_variance':float(w)}
    (ROOT/'user_sim_compare_summary.json').write_text(json.dumps(summary,ensure_ascii=False,indent=2),encoding='utf8')
    print('sim compare 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))
