"""Banco reproducible de llamadas con llama-cpp-python. No ejecuta operaciones externas."""
from __future__ import annotations
import argparse
import hashlib
import json
from pathlib import Path
import re
import time
import llama_cpp

from llama_cpp import Llama, LlamaGrammar
from tool_bank import make_cases, tool_bank, retrieve_tools, validate_call


def parse_unique(text):
    def pairs(items):
        result = {}
        for key, value in items:
            if key in result:
                raise ValueError('duplicate key: ' + key)
            result[key] = value
        return result
    try:
        return json.loads(text, object_pairs_hook=pairs)
    except (ValueError, TypeError) as exc:
        raise ValueError('invalid JSON: ' + str(exc)) from exc


def call_schema(tools):
    # El esquema fuerza la estructura general; los parámetros específicos
    # se validan después, porque una gramática no garantiza semántica.
    return {'type': 'object', 'properties': {
        'name': {'type': 'string', 'enum': [t['name'] for t in tools]},
        'arguments': {'type': 'object'}},
        'required': ['name', 'arguments'], 'additionalProperties': False}


def run_one(model, row, bank, constrained, retry):
    started = time.perf_counter()
    schemas = json.dumps(bank, ensure_ascii=False, separators=(',', ':'))
    system = ('Choose exactly one tool for the user request. Return only a JSON object '
              'with keys name and arguments. Use the exact argument values requested. '
              'Available tool schemas: ' + schemas)
    messages = [{'role': 'system', 'content': system}, {'role': 'user', 'content': row['question']}]
    schema=call_schema(bank)
    grammar = ((model.grammar_from_schema(schema) if hasattr(model,'grammar_from_schema')
                else LlamaGrammar.from_json_schema(json.dumps(schema), verbose=False)) if constrained else None)
    attempts = []
    for attempt in range(2 if retry else 1):
        call_started = time.perf_counter()
        response = model.create_chat_completion(messages=messages, max_tokens=128,
                    temperature=0, seed=1000 + row['id'], grammar=grammar)
        call_seconds = time.perf_counter() - call_started
        text = response['choices'][0]['message'].get('content') or ''
        usage = response.get('usage', {})
        if any(type(usage.get(k)) is not int or usage[k]<0 for k in ('prompt_tokens','completion_tokens')):
            raise RuntimeError('model token usage missing or invalid')
        try:
            proposal = parse_unique(text)
            valid, error = validate_call(proposal, bank)
        except ValueError as exc:
            proposal, valid, error = None, False, str(exc)
        attempts.append({'raw': text, 'proposal': proposal, 'valid': valid,
                         'error': error, 'usage': usage,'seconds':call_seconds})
        if valid:
            break
        messages.extend([{'role': 'assistant', 'content': text},
                         {'role': 'user', 'content': 'Validation error: ' + error + '. Return a corrected JSON object.'}])
    def classify(attempt):
        proposal, valid = attempt['proposal'], attempt['valid']
        correct_name = valid and proposal['name'] == row['expected']['name']
        exact = correct_name and proposal['arguments'] == row['expected']['arguments']
        return {'valid':bool(valid), 'correct_name':bool(correct_name), 'exact':bool(exact)}
    initial, final = classify(attempts[0]), classify(attempts[-1])
    return {'id': row['id'], 'family': row['family'], 'constrained': constrained,
            'retry': retry, 'initial':initial, 'final':final,
            'retrieved': any(t['name'] == row['expected']['name'] for t in bank),
            'attempts': attempts,'seconds':time.perf_counter()-started}


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--model', required=True)
    parser.add_argument('--output', required=True)
    parser.add_argument('--limit', type=int, default=150)
    parser.add_argument('--context', type=int, default=8192)
    parser.add_argument('--gpu-layers', type=int, default=0)
    args = parser.parse_args()
    if not 1 <= args.limit <= 150:
        raise ValueError('limit must be between 1 and 150')
    model_file = Path(args.model)
    split = re.match(r'^(.*)-(\d{5})-of-(\d{5})\.gguf$', model_file.name)
    if split:
        stem, index, total = split.groups()
        if int(index) != 1: raise ValueError('pass the first GGUF shard')
        model_files = [model_file.with_name(f'{stem}-{i:05d}-of-{int(total):05d}.gguf') for i in range(1,int(total)+1)]
    else:
        model_files = [model_file]
    hashes={}
    for path in model_files:
        digest=hashlib.sha256()
        with path.open('rb') as handle:
            for block in iter(lambda:handle.read(1024 * 1024),b''):
                digest.update(block)
        hashes[path.name]=digest.hexdigest()
    model = Llama(model_path=str(model_file), n_ctx=args.context, n_gpu_layers=args.gpu_layers, verbose=False)
    output = Path(args.output)
    meta = {'protocol':2, 'model_file': model_file.name, 'model_sha256': hashes,
            'llama_cpp':llama_cpp.__version__, 'context': args.context, 'gpu_layers': args.gpu_layers,
            'limit': args.limit, 'temperature': 0, 'max_tokens': 128}
    completed=set()
    if output.exists():
        lines=output.read_text(encoding='utf-8').splitlines()
        if not lines or json.loads(lines[0]) != {'metadata':meta}:
            raise ValueError('existing campaign metadata differs')
        for line in lines[1:]:
            item=json.loads(line)
            key=(item['mode'],item['constrained'],item['id'])
            if key in completed: raise ValueError('duplicate campaign row')
            completed.add(key)
    with output.open('a', encoding='utf-8') as handle:
        if not completed and output.stat().st_size == 0:
            handle.write(json.dumps({'metadata': meta}, ensure_ascii=False) + '\n')
            handle.flush()
        for mode in ('8', '60', '60-retrieved'):
            for restricted in (False, True):
                for row in make_cases(args.limit):
                    if (mode,restricted,row['id']) in completed: continue
                    tools = tool_bank(8 if mode == '8' else 60)
                    if mode == '60-retrieved':
                        tools = retrieve_tools(row['question'], tools, 8)
                    result = run_one(model, row, tools, restricted, True)
                    result['mode'] = mode
                    handle.write(json.dumps(result, ensure_ascii=False) + '\n')
                    handle.flush()
                    print(mode, restricted, row['id'], result['initial']['exact'], result['final']['exact'], flush=True)


if __name__ == '__main__':
    main()
