"""BFCL v4, 10 primeros casos simple_python, comprobador AST propio conservador."""
import ast,json,time
from pathlib import Path

ROOT=Path('agent-bench');ROOT.mkdir(parents=True,exist_ok=True)
def function_name(node):
    if isinstance(node,ast.Name):return node.id
    if isinstance(node,ast.Attribute):return function_name(node.value)+'.'+node.attr
    raise ValueError('nombre no admitido')
def equivalent(a,b):
    if type(a) is bool or type(b) is bool:return type(a) is type(b) and a==b
    if type(a) in (int,float) and type(b) in (int,float):return a==b
    return type(a) is type(b) and a==b
def check(text,expected):
    try:
        tree=ast.parse(text.strip(),mode='eval').body
        if not isinstance(tree,ast.Call) or tree.args or any(k.arg is None for k in tree.keywords):return False
        values={k.arg:ast.literal_eval(k.value) for k in tree.keywords}
        if len(values)!=len(tree.keywords):return False
        name=function_name(tree.func)
        for option in expected:
            if name not in option:continue
            accepted=option[name]
            if set(values)-set(accepted):continue
            if all((key in values and any(equivalent(values[key],v) for v in alternatives)) or
                   (key not in values and '' in alternatives) for key,alternatives in accepted.items()):return True
        return False
    except (ValueError,TypeError,SyntaxError,RecursionError):return False
def run(model,tok):
    import torch
    questions=[json.loads(s) for s in (ROOT/'bfcl-questions.jsonl').read_text(encoding='utf-8').splitlines()][:10]
    answers={x['id']:x['ground_truth'] for x in (json.loads(s) for s in (ROOT/'bfcl-answers.jsonl').read_text(encoding='utf-8').splitlines())}
    path=ROOT/'bfcl-results.json';out=json.loads(path.read_text(encoding='utf-8')) if path.exists() else []
    done={r['id'] for r in out}
    for r in questions:
        if r['id'] in done:continue
        prompt=('Choose the appropriate function and arguments. Return exactly one Python function call with keyword arguments; '
                'do not execute it or return an explanation.\nFunctions: '+json.dumps(r['function'],ensure_ascii=False)+
                '\nRequest: '+r['question'][0][0]['content'])
        chat=tok.apply_chat_template([{'role':'user','content':prompt}],tokenize=False,add_generation_prompt=True)
        batch=tok(chat,return_tensors='pt').to('cuda');start=time.perf_counter()
        with torch.no_grad(): generated=model.generate(**batch,max_new_tokens=80,do_sample=False,pad_token_id=tok.eos_token_id)
        raw=tok.decode(generated[0,batch['input_ids'].shape[1]:],skip_special_tokens=True).strip()
        out.append({'id':r['id'],'prompt':prompt,'answer':raw,'expected':answers[r['id']],
                    'success':check(raw,answers[r['id']]),'input_tokens':int(batch['input_ids'].shape[1]),
                    'output_tokens':int(generated.shape[1]-batch['input_ids'].shape[1]),'seconds':time.perf_counter()-start})
        path.write_text(json.dumps(out,ensure_ascii=False,indent=2),encoding='utf-8')
        print('BFCL',r['id'],out[-1]['success'],repr(raw),flush=True)
    print('BFCL subset',sum(x['success'] for x in out),'/',len(out),flush=True)

if __name__=='__main__':
    import hashlib,requests
    base='https://raw.githubusercontent.com/ShishirPatil/gorilla/6ea57973c7a6097fd7c5915698c54c17c5b1b6c8/berkeley-function-call-leaderboard/bfcl_eval/data/'
    for name,url,digest in [('bfcl-questions.jsonl','BFCL_v4_simple_python.json','82dd63ba502eb2520c6b5d1d9a5c4b590e03ff261565175561f6228a367d1991'),('bfcl-answers.jsonl','possible_answer/BFCL_v4_simple_python.json','90cd5bc653690ee8e459b5b3f3fc9458606f7f3fcbf795bb51b7dc581f8c86dc')]:
        p=ROOT/name
        if not p.exists():
            response=requests.get(base+url,timeout=90);response.raise_for_status();p.write_bytes(response.content)
        if hashlib.sha256(p.read_bytes()).hexdigest()!=digest:raise ValueError('Hash BFCL inesperado')

if __name__=='__main__':
    import torch
    from transformers import AutoTokenizer,AutoModelForCausalLM,BitsAndBytesConfig
    name='Qwen/Qwen2.5-7B-Instruct';rev='a09a35458c702b33eeacc393d103063234e8bc28'
    tok=AutoTokenizer.from_pretrained(name,revision=rev)
    cfg=BitsAndBytesConfig(load_in_4bit=True,bnb_4bit_quant_type='nf4',bnb_4bit_compute_dtype=torch.float16)
    model=AutoModelForCausalLM.from_pretrained(name,revision=rev,quantization_config=cfg,device_map={'':0},dtype=torch.float16).eval()
    run(model,tok)
