"""Juez independiente del primer pase: clasifica 30 eventos del orquestador."""
import json,re
from pathlib import Path
import torch
ROOT=Path('.')
def run(model,tok):
 candidates=json.loads((ROOT/'component-traces.json').read_text(encoding='utf8'))['components']
 cases=json.loads((ROOT/'orchestrator-results.json').read_text(encoding='utf8'))
 path=ROOT/'component_judge.json';out=json.loads(path.read_text(encoding='utf8')) if path.exists() else []
 done={x['id'] for x in out}
 for item in candidates:
  if item['id'] in done:continue
  index=int(item['id'].split('-',1)[0]);events=cases[index]['multi']['events']
  context='\n'.join(name+': '+event['text'] for name,event in zip(('split','branch0','branch1','synthesis'),events))
  prompt=('Classify the most visible failure in the target component, using the trace. '
          'SYSTEM: incomplete execution or failure of the decomposition contract. '
          'INTERACTION: information lost or miscommunicated between components. '
          'VERIFICATION: unsupported inference, contradiction or malformed citation. '
          'UNKNOWN: insufficient evidence. Reply with exactly one category.\nQuestion: '+item['question']+
          '\nReference: '+item['reference']+'\nTarget: '+item['node']+'\nTrace:\n'+context)
  chat=tok.apply_chat_template([{'role':'user','content':prompt}],tokenize=False,add_generation_prompt=True)
  batch=tok(chat,return_tensors='pt').to('cuda')
  with torch.no_grad():result=model.generate(**batch,max_new_tokens=6,do_sample=False,pad_token_id=tok.eos_token_id)
  raw=tok.decode(result[0,batch['input_ids'].shape[1]:],skip_special_tokens=True).strip()
  match=re.match(r'^(SYSTEM|INTERACTION|VERIFICATION|UNKNOWN)\b',raw,re.I)
  out.append({'id':item['id'],'raw':raw,'label':match.group(1).upper() if match else None,
              'input_tokens':int(batch['input_ids'].shape[1]),'output_tokens':int(result.shape[1]-batch['input_ids'].shape[1])})
  path.write_text(json.dumps(out,ensure_ascii=False,indent=2),encoding='utf8')
  print('component judge',len(out),item['id'],raw,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))
