"""Ejecuta evaluador-optimizador real con el motor durable de la lección."""
import asyncio,importlib.util,json,sys,time,uuid
from pathlib import Path
import torch
ROOT=Path('workflow-lab');ROOT.mkdir(parents=True,exist_ok=True)
def run(model,tok):
    spec=importlib.util.spec_from_file_location('workflow25',Path('workflow_engine.py'))
    wf=importlib.util.module_from_spec(spec);sys.modules[spec.name]=wf;spec.loader.exec_module(wf)
    question=json.loads((ROOT/'gsm8k-test.jsonl').read_text(encoding='utf8').splitlines()[20])['question']
    calls=[]
    def ask(prompt):
        chat=tok.apply_chat_template([{'role':'user','content':prompt}],tokenize=False,add_generation_prompt=True)
        batch=tok(chat,return_tensors='pt').to('cuda');torch.cuda.synchronize();start=time.perf_counter()
        with torch.no_grad():out=model.generate(**batch,max_new_tokens=96,do_sample=False,pad_token_id=tok.eos_token_id)
        torch.cuda.synchronize()
        tokens=out[0,batch['input_ids'].shape[1]:];text=tok.decode(tokens,skip_special_tokens=True).strip()
        result={'prompt':prompt,'text':text,'input_tokens':int(batch['input_ids'].shape[1]),'output_tokens':int(len(tokens)),
                'seconds':time.perf_counter()-start}
        calls.append(result);return result
    def step(patch,result):
        # Tarifa ficticia uniforme para hacer explícito el cálculo de coste.
        cost=(result['input_tokens']+result['output_tokens'])/1_000_000
        return wf.StepResult(patch,result['input_tokens'],result['output_tokens'],cost)
    async def draft(state):
        r=ask('Solve this problem.\n'+question);return step({'draft':r['text']},r)
    async def critic(state):
        r=ask('Check the proposed solution and identify any error.\nQuestion: '+question+'\nDraft: '+state['draft'])
        return step({'review':r['text']},r)
    async def revise(state):
        r=ask('Give a corrected answer. Finish with FINAL: number.\nQuestion: '+question+'\nDraft: '+state['draft']+'\nReview: '+state['review'])
        return step({'answer':r['text']},r)
    nodes=[wf.Node('draft',(),draft),wf.Node('critic',('draft',),critic),wf.Node('revise',('critic',),revise)]
    store=wf.Store(str(ROOT/'workflow_real.sqlite'));run_id='workflow-'+uuid.uuid4().hex
    result=asyncio.run(wf.run_graph(nodes,run_id,store,{'question':question}))
    events=store.db.execute('SELECT node,event,data FROM events WHERE run_id=? ORDER BY seq',(run_id,)).fetchall()
    data={'question':question,'state':result['state'],'calls':calls,
          'events':[{'node':n,'event':e,'data':json.loads(d)} for n,e,d in events],
          'cost_note':'tarifa hipotética una unidad por millón de tokens'}
    assert all(e['data']['input_tokens']==c['input_tokens'] and e['data']['output_tokens']==c['output_tokens'] for e,c in zip(data['events'],calls))
    (ROOT/'workflow_real.json').write_text(json.dumps(data,ensure_ascii=False,indent=2),encoding='utf8')
    store.export_jsonl(run_id,str(ROOT/'workflow_real_trace.jsonl'));store.db.close()
    print('workflow evaluator',len(calls),'nodos con tokens y coste',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))
