"""Juez 7B por servidor local; dos herramientas de lectura sobre 50 trazas."""
import json
import os
from pathlib import Path
from urllib.request import Request, ProxyHandler, HTTPRedirectHandler, build_opener
from annotated50 import annotated

MODEL='qwen2.5-7b-instruct-q4_k_m-00001-of-00002.gguf'
REV='bb5d59e06d9551d752d08b292a50eb208b07ab1f'
LABELS={'exito','final','formato','herramienta','observacion'}
local=Path(__file__).with_name('agent-runs.json')
source=local if local.exists() else next((p/'public/data/m23/l27/agent-runs.json' for p in Path(__file__).resolve().parents if (p/'public/data/m23/l27/agent-runs.json').exists()),None)
if source is None: raise FileNotFoundError('download agent-runs.json alongside this script')
rows=annotated(json.loads(source.read_text(encoding='utf-8')))
destination=Path(os.environ.get('ORYON_JUDGE_OUTPUT','judge50-7b.jsonl'))
port=int(os.environ.get('ORYON_JUDGE_PORT','11441'))

class NoRedirect(HTTPRedirectHandler):
    def redirect_request(self,*args,**kwargs): raise RuntimeError('redirección no permitida')

def generate(messages,max_new):
    data=json.dumps({'model':MODEL,'messages':messages,'temperature':0,'max_tokens':max_new}).encode('utf-8')
    req=Request(f'http://127.0.0.1:{port}/v1/chat/completions',data=data,headers={'Content-Type':'application/json'})
    with build_opener(ProxyHandler({}),NoRedirect()).open(req,timeout=900) as response:
        body=json.load(response)
    content=body['choices'][0]['message'].get('content')
    usage=body.get('usage',{})
    return {'text':content.strip() if isinstance(content,str) else '',
            'input_tokens':usage.get('prompt_tokens'),'output_tokens':usage.get('completion_tokens'),
            'timings':body.get('timings',{})}

def summarize(row):
    a=row['agent']
    if row['variant']=='react': events=[{k:e.get(k) for k in ('action','observation','final','error')} for e in a['events']]
    else: events=[{k:a.get(k) for k in ('raw','observation','error')}]
    return json.dumps(events,ensure_ascii=False)

system=('Classify an agent trace. Choose exactly one label: exito if the checker says success; '
        'herramienta if a tool is unknown or errors; formato if parsing or response format fails; '
        'observacion if a tool succeeds but the task remains unfinished; final if it ends without a useful action. '
        'When several apply, use this priority: exito, herramienta, formato, observacion, final.')

def main():
    completed=set()
    if destination.exists():
        for line in destination.read_text(encoding='utf-8').splitlines():
            row=json.loads(line)
            if row['model']!=MODEL or row['revision']!=REV: raise ValueError('different judge model')
            if row['index'] in completed: raise ValueError('duplicate record')
            if not 0<=row['index']<len(rows): raise ValueError('index outside annotation set')
            reference=rows[row['index']]
            if (row['task'],row['variant'],row['attempt'],row['reference']) != (reference['task'],reference['variant'],reference['attempt'],reference['label']):
                raise ValueError('annotation set changed')
            completed.add(row['index'])
    with destination.open('a',encoding='utf-8') as output:
        for index,row in enumerate(rows):
            if index in completed: continue
            messages=[{'role':'system','content':system},{'role':'user','content':
                'First choose one read-only inspection tool: reply exactly {"tool":"events"} or {"tool":"state"}.'}]
            choice=generate(messages,32)
            try:
                parsed=json.loads(choice['text'])
                tool=parsed['tool'] if isinstance(parsed,dict) and set(parsed)=={'tool'} else None
            except (ValueError,TypeError,KeyError): tool=None
            if tool not in ('events','state'):
                decision={'text':'','input_tokens':0,'output_tokens':0}; prediction='invalid_tool'
            else:
                observation=summarize(row) if tool=='events' else json.dumps({'success':row['success_checker']})
                messages += [{'role':'assistant','content':choice['text']},
                             {'role':'user','content':'Tool '+tool+' returned: '+observation+
                              '\nChecker success: '+str(row['success_checker'])+
                              '. Reply with exactly one label, no explanation.'}]
                decision=generate(messages,12)
                prediction=decision['text'].strip().lower()
                if prediction not in LABELS: prediction='invalid_label'
            event={'index':index,'task':row['task'],'variant':row['variant'],'attempt':row['attempt'],
                   'model':MODEL,'revision':REV,'device':'cpu','reference':row['label'],
                   'reference_annotator':'assistant','tool_choice':choice,'decision':decision,'prediction':prediction}
            output.write(json.dumps(event,ensure_ascii=False)+'\n'); output.flush()
            print(index,prediction,row['label'],flush=True)

if __name__=='__main__': main()
