"""Comparación local de dos sistemas sobre 60 CSV propios y operaciones inocuas."""
import json
import os
from pathlib import Path
import sys
import time

import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
from csv_tasks import build_tasks
from csv_tools import tools_for
from plan_executor import execute_plan

local=Path(__file__).resolve().parent
sys.path.insert(0,str(local))
repo_engine=next((p/'src/widgets/m23/l13' for p in local.parents if (p/'src/widgets/m23/l13/react_engine.py').exists()),None)
if repo_engine is not None: sys.path.insert(0,str(repo_engine))
from react_engine import PolicyResponse, run_agent

MODEL='Qwen/Qwen2.5-0.5B-Instruct'
REV='7ae557604adf67be50417f59c2c2f167def9a775'
torch.set_num_threads(4)
device=os.environ.get('ORYON_PLAN_DEVICE','cpu')
tok=None
model=None

def load_model():
    global tok,model
    tok=AutoTokenizer.from_pretrained(MODEL,revision=REV,local_files_only=True)
    model=AutoModelForCausalLM.from_pretrained(MODEL,revision=REV,local_files_only=True,
        dtype=torch.float32 if device=='cpu' else torch.bfloat16).to(device).eval()

def encode(messages):
    result=tok.apply_chat_template(messages,add_generation_prompt=True,return_tensors='pt')
    return result['input_ids'] if hasattr(result,'keys') else result

def count(messages): return int(encode(messages).shape[1])

def generate(messages, limit):
    ids=encode(messages).to(device)
    with torch.inference_mode():
        out=model.generate(input_ids=ids,do_sample=False,max_new_tokens=limit,pad_token_id=tok.eos_token_id)
    continuation=out[0,ids.shape[1]:]
    return PolicyResponse(tok.decode(continuation,skip_special_tokens=True).strip(),ids.shape[1],len(continuation))

instructions=('Tool query takes a JSON string: op must be sum_amount, '
 'count_rows, max_amount or sum_active. Optional region is north or south; optional min_units '
 'is an integer. It reads sales.csv; sum_active joins clients.csv by id and filters active=1. '
 'Tool combine takes a JSON string with op add or subtract and integer fields a and b. '
 'Return the numeric result, not an explanation.')

def react(task):
    result=run_agent(task['question']+' '+instructions,generate,tools_for(task['directory']),count,
        max_steps=4,max_total_tokens=4096,max_context_tokens=2048,max_new_tokens=128,timeout_seconds=600)
    if result['stop_reason'] in ('policy_error','context_prepare_error'):
        raise RuntimeError('agent adapter or policy failure: '+json.dumps(result['events'],ensure_ascii=False))
    return {'answer':result['answer'],'tokens':result['tokens_used'],'trace':result}

def planned(task):
    prompt=[{'role':'system','content':'Output only JSON with key nodes. Each node has id, deps (list), tool (query or combine), and argument (object). In an argument a dependency result may be {"ref":"node_id"}; list that node in deps. The final node result is the answer. '+instructions},
            {'role':'user','content':task['question']}]
    record={'answer':None,'tokens':0,'attempts':[]}
    cache={}; tools=tools_for(task['directory'])
    for _ in range(4):
        context_tokens=count(prompt)
        remaining=min(4096-record['tokens']-context_tokens,2048-context_tokens)
        if remaining<1:
            record['stop_reason']='token_budget'; break
        response=generate(prompt,min(128,remaining))
        record['tokens']+=response.input_tokens+response.output_tokens
        attempt={'raw':response.text,'input_tokens':response.input_tokens,'output_tokens':response.output_tokens}
        record['attempts'].append(attempt)
        try:
            obj=json.loads(response.text)
            if not isinstance(obj,dict) or set(obj)!={'nodes'} or not isinstance(obj['nodes'],list) or not 1<=len(obj['nodes'])<=4:
                raise ValueError('invalid plan')
            nodes=obj['nodes']
            execution=execute_plan(nodes,tools,cache)
            attempt['execution']=execution
            last=nodes[-1]['id']
            if all(status=='ok' for status in execution['status'].values()):
                record['answer']=execution['values'][last]; record['stop_reason']='completed'; break
            feedback='Execution failed: '+json.dumps(execution['errors'])
        except (ValueError,TypeError,KeyError) as exc:
            feedback='Invalid plan: '+type(exc).__name__
        attempt['feedback']=feedback
        prompt.extend([{'role':'assistant','content':response.text},
                       {'role':'user','content':feedback+'. Repair the plan.'}])
    else:
        record['stop_reason']='step_budget'
    return record

def main():
    load_model()
    output=Path(os.environ.get('ORYON_PLAN_OUTPUT','plan-comparison.jsonl'))
    data_root=Path(os.environ.get('ORYON_PLAN_DATA','plan-csv'))
    tasks=build_tasks(data_root,60,905)
    completed=set()
    if output.exists():
        for line in output.read_text(encoding='utf-8').splitlines():
            r=json.loads(line)
            if (r['model'],r['revision'],r['device'])!=(MODEL,REV,device): raise ValueError('model or device mismatch')
            key=(r['variant'],r['id'])
            if key in completed: raise ValueError('duplicate record')
            completed.add(key)
    with output.open('a',encoding='utf-8') as f:
        for task in tasks:
            for name,agent in [('react',react),('plan',planned)]:
                if (name,task['id']) in completed: continue
                start=time.perf_counter(); result=agent(task)
                raw=result['answer']; answer=str(raw).strip() if raw is not None else ''
                correct=answer==str(task['answer'])
                row={'id':task['id'],'family':task['family'],'variant':name,'model':MODEL,'revision':REV,
                     'device':device,'question':task['question'],'expected':task['answer'],
                     'correct':correct,'seconds':time.perf_counter()-start,**result}
                f.write(json.dumps(row,ensure_ascii=False)+'\n'); f.flush()
                print(name,task['id'],correct,flush=True)

if __name__=='__main__':main()
