"""Medición pareada de un arnés local sobre el benchmark ficticio de l27."""
import json
from pathlib import Path
import sys
import time
from urllib.request import Request, ProxyHandler, HTTPRedirectHandler, build_opener

HERE=Path(__file__).resolve().parent
HARNESS=next((p/'public/data/m23/l27' for p in HERE.parents if (p/'public/data/m23/l27/harness.py').exists()),HERE)
sys.path.insert(0,str(HARNESS))
import harness
from audit import PolynomialEnvironment

MODEL='qwen2.5-7b-instruct-q4_k_m-00001-of-00002.gguf'
REV='bb5d59e06d9551d752d08b292a50eb208b07ab1f'
CONDITIONS={'baseline':('string','neutral',3),'tool_format':('object','neutral',3),
            'system_prompt':('string','careful',3),'step_budget':('string','neutral',6)}

class NoRedirect(HTTPRedirectHandler):
    def redirect_request(self,*a,**k): raise RuntimeError('redirect prohibited')

def generate(messages,seed,port):
    request=Request(f'http://127.0.0.1:{port}/v1/chat/completions',
        data=json.dumps({'model':MODEL,'messages':messages,'temperature':0,'seed':seed,'max_tokens':128}).encode(),
        headers={'Content-Type':'application/json'})
    with build_opener(ProxyHandler({}),NoRedirect()).open(request,timeout=900) as response: data=json.load(response)
    if data.get('model')!=MODEL: raise ValueError('unexpected model')
    return data['choices'][0]['message'].get('content') or '',data.get('usage',{})

def parse(text,format):
    def unique(pairs):
        d={}
        for k,v in pairs:
            if k in d: raise ValueError('duplicate key')
            d[k]=v
        return d
    obj=json.loads(text,object_pairs_hook=unique)
    if not isinstance(obj,dict): raise ValueError('expected object')
    if set(obj)=={'final'} and isinstance(obj['final'],str):return ('final',obj['final'])
    if set(obj)!={'action','argument'} or not isinstance(obj['action'],str):raise ValueError('invalid fields')
    arg=obj['argument']
    if format=='string' and not isinstance(arg,str):raise ValueError('argument must be string')
    if format=='object':
        if obj['action']=='read' and isinstance(arg,str):pass
        elif obj['action'] in ('write','db') and isinstance(arg,dict):arg=json.dumps(arg,ensure_ascii=False)
        else:raise ValueError('argument type')
    return obj['action'],arg

def execute(task,condition,generate_fn):
    format,prompt,budget=CONDITIONS[condition]
    system=('Return exactly one JSON action or final per turn. Tools: read(filename), '
            'write({path,content}), db({op,id,amount}). ' +
            ('For read, argument is the plain filename string; for write and db, argument is a JSON object serialized as a string. ' if format=='string' else 'For read, argument is the plain filename string; for write and db, argument is a JSON object. ') +
            ('Check tool observations and correct failures before finishing. ' if prompt=='careful' else '')+
            'Return {"action":"name","argument":...} or {"final":"done"}.')
    messages=[{'role':'system','content':system},{'role':'user','content':task.instruction}]
    env=PolynomialEnvironment(task); events=[]; first_success=None; total_tokens=0; errors=0; recovered=False; prior_error=False
    started=time.perf_counter()
    try:
        for step in range(budget):
            text,usage=generate_fn(messages,280000+task.seed*10+step)
            if type(usage.get('total_tokens')) is not int or usage['total_tokens']<0:
                raise RuntimeError('model token usage missing or invalid')
            total_tokens+=usage['total_tokens']
            event={'step':step,'raw':text,'usage':usage}; error=None
            try:
                action,arg=parse(text,format)
                if action=='final': event['final']=arg; events.append(event); break
                if action not in ('read','write','db'): raise ValueError('unknown tool')
                observation=getattr(env,action)(arg)
                event.update(action=action,observation=observation)
                if prior_error: recovered=True; prior_error=False
            except (ValueError,TypeError,KeyError,json.JSONDecodeError) as exc:
                error=type(exc).__name__; errors+=1; prior_error=True
                observation='Error: '+error; event['error']=error
            ok,_=env.check(); event['checker_success']=bool(ok)
            if ok and first_success is None:first_success=step+1
            events.append(event)
            messages.extend([{'role':'assistant','content':text},{'role':'user','content':'Tool observation: '+str(observation)}])
        success,check=env.check()
        return {'task':task.id,'family':task.kind,'condition':condition,'success':bool(success),
                'checker':check,'first_success_step':first_success,'tool_or_format_errors':errors,
                'successful_tool_after_error':recovered,'tokens':total_tokens,'events':events,
                'model':MODEL,'revision':REV,'seconds':time.perf_counter()-started,
                'temperature':0,'max_new_tokens_per_turn':128,'budget_steps':budget}
    finally:env.close()

def run(output,generate_fn,limit=None):
    path=Path(output);done=set()
    if path.exists():
        for line in path.read_text(encoding='utf8').splitlines():
            r=json.loads(line); key=(r['task'],r['condition'])
            if key in done or (r['model'],r['revision'])!=(MODEL,REV):raise ValueError('existing rows invalid')
            done.add(key)
    completed=0
    with path.open('a',encoding='utf8') as out:
        for task in harness.tasks():
            for condition in CONDITIONS:
                if (task.id,condition) in done:continue
                row=execute(task,condition,generate_fn)
                out.write(json.dumps(row,ensure_ascii=False)+'\n');out.flush()
                print(task.id,condition,row['success'],round(row['seconds'],2),flush=True)
                completed+=1
                if limit is not None and completed>=limit:return

if __name__=='__main__':
    import argparse
    p=argparse.ArgumentParser();p.add_argument('--output',required=True);p.add_argument('--port',type=int,default=11441)
    p.add_argument('--limit',type=int,help='número máximo de nuevas trayectorias en este bloque')
    args=p.parse_args()
    if args.limit is not None and args.limit<1:p.error('--limit debe ser positivo')
    run(args.output,lambda messages,seed:generate(messages,seed,args.port),args.limit)
