"""Latencia y RSS CPU comparables para GGUF BF16 y Q4, con el mismo servidor y avisos."""
import hashlib
import json
import os
from pathlib import Path
import platform
import socket
import statistics
import subprocess
import threading
import time
from urllib.error import URLError
from urllib.request import Request, urlopen

import psutil
from transformers import AutoTokenizer

EXPORT = Path(os.environ['P08_EXPORT_DIR'])
SFT = Path(os.environ['P08_L04_DIR'])
SERVER = Path(os.environ['P08_LLAMA_SERVER'])
REV = '7ae557604adf67be50417f59c2c2f167def9a775'
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 file:
        for part in iter(lambda: file.read(8 * 1024 * 1024), b''): h.update(part)
    return h.hexdigest()


def run_one(name, weights, prompts, out):
    with socket.socket() as sock:
        sock.bind(('127.0.0.1', 0)); port = sock.getsockname()[1]
    url = f'http://127.0.0.1:{port}'
    samples, maximum = [], [0]
    stop = threading.Event()
    with (out / f'benchmark-{name}.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)],
                                stdout=log, stderr=subprocess.STDOUT)
        def monitor():
            process = psutil.Process(proc.pid)
            while not stop.wait(0.25):
                try: maximum[0] = max(maximum[0], process.memory_info().rss)
                except psutil.Error: break
        thread = threading.Thread(target=monitor, daemon=True); thread.start()
        try:
            while True:
                if proc.poll() is not None: raise RuntimeError(f'El servidor {name} terminó')
                try:
                    with urlopen(url + '/health', timeout=5) as response:
                        if json.load(response).get('status') == 'ok': break
                except (URLError, TimeoutError): pass
                time.sleep(1)
            # Se calienta con el primer aviso, sin contabilizarlo entre las ocho medidas.
            for index, prompt in enumerate([prompts[0], *prompts]):
                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(url + '/completion', data=body, headers={'Content-Type': 'application/json'}),
                             timeout=600) as response: result = json.load(response)
                elapsed = time.perf_counter() - start
                if index:
                    samples.append({'id': index - 1, 'seconds': elapsed, 'content': result['content'],
                                    'tokens_evaluated': result.get('tokens_evaluated'),
                                    'tokens_predicted': result.get('tokens_predicted'),
                                    'timings': result.get('timings')})
        finally:
            proc.terminate()
            try: proc.wait(timeout=15)
            except subprocess.TimeoutExpired: proc.kill(); proc.wait()
            stop.set(); thread.join()
    return {'rows': samples, 'median_seconds': statistics.median(row['seconds'] for row in samples),
            'peak_rss_sampled_bytes': maximum[0], 'rss_sampling_seconds': 0.25}


def main():
    path = EXPORT / 'benchmark-bf16-q4.json'
    if path.exists(): raise FileExistsError(path)
    manifest = json.loads((EXPORT / 'manifest.json').read_text(encoding='utf-8'))
    weights = {'bf16': EXPORT / 'merged-bf16.gguf', 'q4': EXPORT / 'merged-q4_k_m.gguf'}
    for key, file in weights.items():
        if sha(file) != manifest['bf16_sha256' if key == 'bf16' else 'q4_k_m_sha256']:
            raise ValueError(f'La huella de {key} no coincide')
    data = json.loads((SFT / 'dev.json').read_text(encoding='utf-8'))[:8]
    if len(data) != 8: raise ValueError('Faltan preguntas de desarrollo')
    tok = AutoTokenizer.from_pretrained('Qwen/Qwen2.5-0.5B-Instruct', revision=REV, local_files_only=True)
    prompts = [tok.apply_chat_template([{'role': 'user', 'content': row['prompt']}], tokenize=False,
                                       add_generation_prompt=True) for row in data]
    result = {'model_hashes': {key: sha(file) for key, file in weights.items()},
              'server_sha256': sha(SERVER), 'hardware': platform.processor(), 'device': 'CPU', 'threads': THREADS,
              'development_ids': [row['id'] for row in data], 'sequential': True, 'concurrency': 1,
              'protocol': 'ocho avisos de desarrollo, calentamiento de uno, 12 tokens máximos, greedy, caché desactivada',
              'latency_note': 'Incluye prefill y HTTP; número de tokens de salida variable.', 'results': {}}
    for key, file in weights.items():
        result['results'][key] = run_one(key, file, prompts, EXPORT)
    temporary = path.with_suffix('.json.tmp')
    with temporary.open('w', encoding='utf-8') as file:
        json.dump(result, file, ensure_ascii=False, indent=2); file.flush(); os.fsync(file.fileno())
    os.replace(temporary, path)
    print('Benchmark guardado:', path, flush=True)


if __name__ == '__main__': main()
