"""Agente ReAct real y servidor local llama.cpp con y sin caché KV efectiva."""
import copy,importlib.util,json,random,sys,threading,time
from http.server import BaseHTTPRequestHandler,HTTPServer
from pathlib import Path
import requests
from huggingface_hub import hf_hub_download
from llama_cpp import Llama
from transformers import AutoTokenizer

ROOT=Path('memory-lab');ROOT.mkdir(parents=True,exist_ok=True)
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)
tok=AutoTokenizer.from_pretrained('Qwen/Qwen2.5-0.5B-Instruct',revision='7ae557604adf67be50417f59c2c2f167def9a775')
model_path=hf_hub_download('Qwen/Qwen2.5-0.5B-Instruct-GGUF','qwen2.5-0.5b-instruct-q4_k_m.gguf',revision='9217f5db79a29953eb74d5343926648285ec7e67')
llm=Llama(model_path=model_path,n_ctx=4096,n_threads=4,verbose=False)
cache_enabled=False;eval_calls=[];prior_eval=llm.eval
def counted(tokens):
    eval_calls.append(len(tokens));return prior_eval(tokens)
llm.eval=counted
class Handler(BaseHTTPRequestHandler):
    def send_json(self,payload,status=200):
        raw=json.dumps(payload,ensure_ascii=False).encode('utf8');self.send_response(status)
        self.send_header('Content-Type','application/json');self.send_header('Content-Length',str(len(raw)));self.end_headers();self.wfile.write(raw)
    def do_POST(self):
        global cache_enabled
        try:
            body=json.loads(self.rfile.read(int(self.headers['Content-Length'])))
            if self.path=='/control':
                cache_enabled=bool(body['cache']);llm.reset();return self.send_json({'cache':cache_enabled})
            if self.path!='/v1/chat/completions':return self.send_json({'error':'path'},404)
            prompt=tok.apply_chat_template(body['messages'],tokenize=False,add_generation_prompt=True)
            expected=len(tok(prompt)['input_ids'])
            if not cache_enabled:llm.reset()
            eval_calls.clear();start=time.perf_counter()
            result=llm.create_completion(prompt=prompt,max_tokens=body['max_tokens'],temperature=0)
            usage=result['usage']
            self.send_json({'choices':[{'message':{'content':result['choices'][0]['text'].strip()}}],
                            'usage':{'prompt_tokens':expected,'completion_tokens':usage['completion_tokens'],
                                     'prefill_evaluated':eval_calls[0],'llama_prompt_tokens':usage['prompt_tokens'],
                                     'eval_calls':eval_calls.copy(),'seconds':time.perf_counter()-start}})
        except Exception as exc:self.send_json({'error':type(exc).__name__+': '+str(exc)},500)
    def log_message(self,fmt,*args):pass

examples=[{'role':'user','content':'Read /people/ada.txt and then the named city file. Answer the country.'},
          {'role':'assistant','content':'{"action":"read","argument":"/people/ada.txt"}'},
          {'role':'user','content':'Observation: Ada works in Tallinn; read /cities/tallinn.txt.'},
          {'role':'assistant','content':'{"action":"read","argument":"/cities/tallinn.txt"}'},
          {'role':'user','content':'Observation: Tallinn is in Estonia.'},
          {'role':'assistant','content':'{"final":"Estonia"}'}]
def serialize(messages):return tok.apply_chat_template([messages[0]]+examples+messages[1:],tokenize=False,add_generation_prompt=True)
def count(messages):return len(tok(serialize(messages))['input_ids'])
def compact(history,mode):
    h=copy.deepcopy(history);pairs=[h[i:i+2] for i in range(2,len(h),2)]
    if mode=='todo':return h
    if mode=='ventana':return h[:2]+sum(pairs[-1:],[])
    if mode=='mascara':
        for pair in pairs[:-1]:pair[1]['content']='Observation: [masked old observation]'
        return h[:2]+sum(pairs,[])
    cut=max(0,((len(pairs)-1)//2)*2)
    if not cut:return h
    old=pairs[:cut];recent=pairs[cut:];notes=' | '.join(p[1]['content'][:180] for p in old)
    fake=[{'role':'assistant','content':'{"thought":"Context manager note follows."}'},
          {'role':'user','content':'Observation: [extractive context-manager note] '+notes}]
    return h[:2]+fake+sum(recent,[])

server=HTTPServer(('127.0.0.1',0),Handler);thread=threading.Thread(target=server.serve_forever,daemon=True);thread.start()
url=f'http://127.0.0.1:{server.server_port}';path=ROOT/'cache_live.json'
records=json.loads(path.read_text(encoding='utf8')) if path.exists() else []
done={(r['person'],r['mode'],r['cache']) for r in records}
try:
    for person,city,country in [('mira','helsinki','Finland'),('lina','lisbon','Portugal'),('toma','oslo','Norway')]:
        fs={f'/people/{person}.txt':f'{person.title()} works in {city.title()}; read /cities/{city}.txt.',
            f'/cities/{city}.txt':f'The country record is /countries/{country.lower()}.txt.',
            f'/countries/{country.lower()}.txt':f'Country: {country}.'}
        question=f'Use read to follow files starting at /people/{person}.txt and answer the country.'
        for mode in ('todo','ventana','mascara','resumen','notas'):
            for cache in (False,True):
                if (person,mode,cache) in done:continue
                requests.post(url+'/control',json={'cache':cache},timeout=30).raise_for_status()
                notes_path=ROOT/f'live-notes-{person}-{mode}-{int(cache)}.txt'
                notes_path.write_text('',encoding='utf8');usages=[]
                def read(path):
                    result=fs.get(path.strip(),'File not found.')
                    with notes_path.open('a',encoding='utf8') as f:f.write(path.strip()+': '+result+'\n')
                    return result
                def prepare(history):return compact(history,'ventana' if mode=='notas' else mode)
                def policy(messages,max_new):
                    r=requests.post(url+'/v1/chat/completions',json={'messages':[messages[0]]+examples+messages[1:],'max_tokens':max_new},timeout=600)
                    r.raise_for_status();body=r.json();usage=body['usage'];usages.append(usage)
                    return engine.PolicyResponse(body['choices'][0]['message']['content'],usage['prompt_tokens'],usage['completion_tokens'],serialize(messages))
                tools={'read':read}
                if mode=='notas':tools['notes']=lambda _: notes_path.read_text(encoding='utf8')
                start=time.perf_counter();result=engine.run_agent(question,policy,tools,count,max_steps=8,max_total_tokens=6000,
                    max_context_tokens=1500,max_new_tokens=96,timeout_seconds=1200,prepare_context=prepare)
                if any(e.get('error')=='policy_error' for e in result['events']):raise RuntimeError('falló el adaptador de servidor')
                record={'person':person,'mode':mode,'cache':cache,'answer':result['answer'],'expected':country,
                        'success':(result['answer'] or '').strip().lower()==country.lower(),'stop_reason':result['stop_reason'],
                        'prefill_evaluated':sum(u['prefill_evaluated'] for u in usages),'prompt_tokens':sum(u['prompt_tokens'] for u in usages),
                        'output_tokens':sum(u['completion_tokens'] for u in usages),'seconds':time.perf_counter()-start,
                        'usages':usages,'result':result}
                records.append(record);path.write_text(json.dumps(records,ensure_ascii=False,indent=2),encoding='utf8')
                print(person,mode,'cache',cache,'éxito',record['success'],'prefill',record['prefill_evaluated'],flush=True)
finally:
    server.shutdown();server.server_close();thread.join()
summary={};rng=random.Random(24)
for mode in ('todo','ventana','mascara','resumen','notas'):
    summary[mode]={}
    for cache in (False,True):
        subset=[r for r in records if r['mode']==mode and r['cache']==cache]
        if len(subset)!=3:raise ValueError('faltan trayectorias')
        a=[int(r['success']) for r in subset];boot=sorted(sum(rng.choice(a) for _ in a)/len(a) for _ in range(2000))
        summary[mode]['cache' if cache else 'sin_cache']={'success':sum(a),'n':3,'ci':[boot[49],boot[1949]],
            'prefill':sum(r['prefill_evaluated'] for r in subset),'decode':sum(r['output_tokens'] for r in subset),
            'seconds':sum(r['seconds'] for r in subset)}
(ROOT/'cache_live_summary.json').write_text(json.dumps(summary,ensure_ascii=False,indent=2),encoding='utf8')
print(summary,flush=True)
