"""Evaluación CWE pareada del GGUF servido por llama.cpp. Pendiente de ejecución."""
import hashlib
import json
import os
import re
import socket
import subprocess
import time
from pathlib import Path
from urllib.error import URLError
from urllib.request import Request, urlopen

import numpy as np
from transformers import AutoTokenizer

SFT = Path(os.environ['P08_L04_DIR'])
EXPORT = Path(os.environ.get('P08_EXPORT_DIR', 'p08-export'))
FINAL = Path(os.environ.get('P08_FINAL_DIR', 'p08-final'))
TOOL = Path(os.environ['P08_LLAMA_SERVER'])
REV = '7ae557604adf67be50417f59c2c2f167def9a775'
MARGIN = 0.05  # Límite práctico decidido antes de observar el conjunto de prueba.
VARIANT = os.environ.get('P08_GGUF_VARIANT', 'q4')
if VARIANT not in ('bf16', 'q4'): raise ValueError('P08_GGUF_VARIANT debe ser bf16 o q4')
THREADS = int(os.environ.get('P08_LLAMA_THREADS', '2'))
if THREADS < 1: raise ValueError('P08_LLAMA_THREADS debe ser positivo')

def sha(path):
    h = hashlib.sha256()
    with path.open('rb') as stream:
        for chunk in iter(lambda: stream.read(8 * 1024 * 1024), b''): h.update(chunk)
    return h.hexdigest()

def main():
    prefix = 'gguf-cwe' if VARIANT == 'q4' else 'gguf-cwe-bf16'
    destination = EXPORT / f'{prefix}-evaluation.json'
    if destination.exists(): raise FileExistsError(destination)
    manifest = json.loads((EXPORT / 'manifest.json').read_text(encoding='utf-8'))
    weights = EXPORT / ('merged-q4_k_m.gguf' if VARIANT == 'q4' else 'merged-bf16.gguf')
    weight_key = 'q4_k_m_sha256' if VARIANT == 'q4' else 'bf16_sha256'
    if sha(weights) != manifest[weight_key]: raise ValueError('La huella GGUF no coincide')
    reference = json.loads((FINAL / 'dpo.json').read_text(encoding='utf-8'))
    data = json.loads((SFT / 'test.json').read_text(encoding='utf-8'))
    ref = reference['results']['cwe']
    if [r['id'] for r in data] != [r['id'] for r in ref]: raise ValueError('IDs no alineados')
    if reference['metadata']['adapter_sha256']['adapter_model.safetensors'] != manifest['adapter_sha256']:
        raise ValueError('La evaluación previa usa otro adaptador')
    if reference['metadata']['base_weights_sha256'] != manifest['base_weights_sha256']:
        raise ValueError('La evaluación previa usa otra base')
    tok = AutoTokenizer.from_pretrained('Qwen/Qwen2.5-0.5B-Instruct', revision=REV, local_files_only=True)
    run_manifest = {'script_sha256': sha(Path(__file__)), 'gguf_sha256': manifest[weight_key], 'variant': VARIANT,
                    'reference_sha256': sha(FINAL / 'dpo.json'), 'tasks_sha256': sha(SFT / 'test.json'),
                    'server_sha256': sha(TOOL), 'n_predict': 12, 'temperature': 0,
                    'repeat_penalty': 1.1, 'repeat_last_n': -1, 'cache_prompt': False, 'gpu_layers': 0, 'threads': THREADS}
    manifest_path, partial = EXPORT / f'{prefix}-manifest.json', EXPORT / f'{prefix}.jsonl'
    if manifest_path.exists():
        if json.loads(manifest_path.read_text(encoding='utf-8')) != run_manifest:
            raise ValueError('La configuración de la evaluación GGUF cambió')
    elif partial.exists():
        raise ValueError('La traza GGUF no tiene manifiesto')
    else:
        temporary = manifest_path.with_suffix('.json.tmp')
        with temporary.open('w', encoding='utf-8') as file:
            json.dump(run_manifest, file, ensure_ascii=False, indent=2); file.flush(); os.fsync(file.fileno())
        os.replace(temporary, manifest_path)
    results = []
    if partial.exists():
        with partial.open(encoding='utf-8') as file:
            for line in file:
                if not line.endswith('\n'): raise ValueError('Traza GGUF con última línea incompleta')
                results.append(json.loads(line))
    if len(results) > len(data) or any(row['id'] != data[i]['id'] for i, row in enumerate(results)):
        raise ValueError('La traza GGUF no coincide con el orden del examen')
    with socket.socket() as sock:
        sock.bind(('127.0.0.1', 0)); port = sock.getsockname()[1]
    base = f'http://127.0.0.1:{port}'
    with (EXPORT / f'{prefix}-server.log').open('a', encoding='utf-8') as log:
        process = subprocess.Popen([str(TOOL), '-m', str(weights), '--host', '127.0.0.1', '--port', str(port),
                                    '-ngl', '0', '--ctx-size', '2048', '--threads', str(THREADS)], stdout=log, stderr=subprocess.STDOUT)
        try:
            while True:
                if process.poll() is not None: raise RuntimeError('Servidor terminó; consultar 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 index in range(len(results), len(data)):
                row = data[index]
                prompt = tok.apply_chat_template([{'role': 'user', 'content': row['prompt']}], tokenize=False,
                                                 add_generation_prompt=True)
                body = json.dumps({'prompt': prompt, 'n_predict': 12, 'temperature': 0,
                                   'repeat_penalty': 1.1, 'repeat_last_n': -1,
                                   'cache_prompt': False}).encode('utf-8')
                start = time.perf_counter()
                with urlopen(Request(base + '/completion', data=body, headers={'Content-Type': 'application/json'}),
                             timeout=600) as response: answer = json.load(response)['content'].strip()
                elapsed = time.perf_counter() - start
                match = re.search(r'CWE-(\d+)', answer)
                entry = {'id': row['id'], 'salida': answer, 'formato': int(bool(match)),
                         'correcto': int(bool(match) and int(match.group(1)) in row['gold']), 'segundos': elapsed}
                with partial.open('a', encoding='utf-8') as file:
                    file.write(json.dumps(entry, ensure_ascii=False) + '\n'); file.flush(); os.fsync(file.fileno())
                results.append(entry)
                if index % 25 == 0: print('GGUF', index, '/', len(data), flush=True)
        finally:
            process.terminate()
            try: process.wait(timeout=15)
            except subprocess.TimeoutExpired:
                process.kill(); process.wait()
    difference = np.array([q['correcto'] - r['correcto'] for q, r in zip(results, ref)], float)
    indexes = np.random.default_rng(0).integers(0, len(difference), (10000, len(difference)))
    ci = np.percentile(difference[indexes].mean(1), [2.5, 97.5]).tolist()
    output = {'gguf_sha256': manifest[weight_key], 'variant': VARIANT, 'referencia_sha256': sha(FINAL / 'dpo.json'),
              'tasks_sha256': sha(SFT / 'test.json'), 'n': len(data), f'delta_{VARIANT}_menos_peft': float(difference.mean()),
              'intervalo_pareado_95': ci, 'margen_practico_prefijado': MARGIN,
              'equivalencia_demostrada': bool(ci[0] > -MARGIN and ci[1] < MARGIN),
              'segundos_mediana': float(np.median([r['segundos'] for r in results])),
              'latencia_nota': 'CPU, incluye prefill y petición HTTP, sin concurrencia; puede combinar sesiones reanudadas y no es prueba de GPU.',
              'rows': results}
    output['evaluation_manifest'] = run_manifest
    temporary = destination.with_suffix('.json.tmp')
    with temporary.open('w', encoding='utf-8') as file:
        json.dump(output, file, ensure_ascii=False, indent=2); file.flush(); os.fsync(file.fileno())
    os.replace(temporary, destination)
    print(json.dumps({k: v for k, v in output.items() if k != 'rows'}, ensure_ascii=False), flush=True)

if __name__ == '__main__': main()
