"""Prueba local de herramienta con el GGUF exportado; conserva también fallos del modelo."""
import hashlib
import json
import os
from pathlib import Path
import socket
import subprocess
import time
from urllib.error import URLError
from urllib.request import Request, urlopen

EXPORT = Path(os.environ['P08_EXPORT_DIR'])
SERVER = Path(os.environ['P08_LLAMA_SERVER'])
THREADS = int(os.environ.get('P08_LLAMA_THREADS', '2'))
if THREADS < 1: raise ValueError('P08_LLAMA_THREADS debe ser positivo')
# Resúmenes didácticos de los nombres del catálogo CWE 5.0 (MITRE).
# https://cwe.mitre.org/data/definitions/79.html (también 89.html y 22.html)
CASES = [
    {'cwe': 'CWE-79', 'description': 'Neutralización incorrecta de entrada durante la generación de una página web.'},
    {'cwe': 'CWE-89', 'description': 'Neutralización incorrecta de elementos especiales en una consulta SQL.'},
    {'cwe': 'CWE-22', 'description': 'Restricción incorrecta de una ruta a un directorio previsto.'},
]
TOOL = {'type': 'function', 'function': {'name': 'consultar_ficha',
    'description': 'Consulta una ficha local por su identificador CWE exacto.',
    'parameters': {'type': 'object', 'properties': {'id': {'type': 'string'}}, 'required': ['id']}}}


def sha(path):
    h = hashlib.sha256()
    with path.open('rb') as f:
        for part in iter(lambda: f.read(8 * 1024 * 1024), b''): h.update(part)
    return h.hexdigest()


def request(base, body):
    raw = json.dumps(body).encode('utf-8')
    with urlopen(Request(base + '/v1/chat/completions', data=raw,
                         headers={'Content-Type': 'application/json'}), timeout=600) as response:
        return json.load(response)


def main():
    result_path = EXPORT / 'agent-tool-demo.json'
    if result_path.exists(): raise FileExistsError(result_path)
    manifest = json.loads((EXPORT / 'manifest.json').read_text(encoding='utf-8'))
    weights = EXPORT / 'merged-q4_k_m.gguf'
    digest = sha(weights)
    if digest != manifest['q4_k_m_sha256']: raise ValueError('Huella GGUF incorrecta')
    with socket.socket() as sock:
        sock.bind(('127.0.0.1', 0)); port = sock.getsockname()[1]
    base = f'http://127.0.0.1:{port}'
    by_id = {row['cwe']: row['description'] for row in CASES}
    rows = []
    with (EXPORT / 'agent-server.log').open('w', encoding='utf-8') as log:
        proc = subprocess.Popen([str(SERVER), '-m', str(weights), '--host', '127.0.0.1', '--port', str(port),
                                 '-ngl', '0', '--ctx-size', '2048', '--threads', str(THREADS), '--jinja'],
                                stdout=log, stderr=subprocess.STDOUT)
        try:
            while True:
                if proc.poll() is not None: raise RuntimeError('Servidor terminado; consultar agent-server.log')
                try:
                    with urlopen(base + '/health', timeout=5) as response:
                        if json.load(response).get('status') == 'ok': break
                except (URLError, TimeoutError): pass
                time.sleep(1)
            for case in CASES:
                messages = [{'role': 'system', 'content': 'Consulta la herramienta antes de explicar la ficha.'},
                            {'role': 'user', 'content': f"Consulta {case['cwe']} y explica brevemente qué significa."}]
                body = {'model': weights.name, 'messages': messages, 'tools': [TOOL],
                        'temperature': 0, 'max_tokens': 160}
                first = request(base, body)
                if first.get('model') != weights.name: raise ValueError('El servidor identifica otro modelo')
                message = first['choices'][0]['message']
                calls = message.get('tool_calls') or []
                row = {'id': case['cwe'], 'first_message': message, 'tool_used_correctly': False,
                       'tool_response': None, 'final_message': None}
                if len(calls) == 1 and calls[0].get('function', {}).get('name') == 'consultar_ficha':
                    try: arguments = json.loads(calls[0]['function']['arguments'])
                    except (TypeError, ValueError): arguments = {}
                    if isinstance(arguments, dict) and arguments.get('id') == case['cwe']:
                        row['tool_used_correctly'] = True
                        messages.append(message)
                        row['tool_response'] = {'id': case['cwe'], 'description': by_id[case['cwe']]}
                        messages.append({'role': 'tool', 'tool_call_id': calls[0]['id'],
                                         'content': json.dumps(row['tool_response'], ensure_ascii=False)})
                        second = request(base, {**body, 'messages': messages})
                        if second.get('model') != weights.name: raise ValueError('El servidor identifica otro modelo')
                        row['final_message'] = second['choices'][0]['message']
                rows.append(row)
                print(case['cwe'], 'herramienta válida:', row['tool_used_correctly'], flush=True)
        finally:
            proc.terminate()
            try: proc.wait(timeout=15)
            except subprocess.TimeoutExpired: proc.kill(); proc.wait()
    result = {'gguf_sha256': digest, 'model_alias': weights.name, 'server': 'llama.cpp', 'threads': THREADS,
              'n': len(rows), 'valid_tool_calls': sum(row['tool_used_correctly'] for row in rows),
              'note': 'Demostración de tres fichas, no batería p05 ni medida general de capacidad de agente.', 'rows': rows}
    tmp = result_path.with_suffix('.json.tmp')
    with tmp.open('w', encoding='utf-8') as f:
        json.dump(result, f, ensure_ascii=False, indent=2); f.flush(); os.fsync(f.fileno())
    os.replace(tmp, result_path)
    print('Resultado:', result_path, flush=True)


if __name__ == '__main__': main()
