"""Compara GGUF BF16 y Q4 en las mismas preguntas CWE, con intervalo pareado."""
import hashlib
import json
import os
from pathlib import Path

import numpy as np

ROOT = Path(os.environ.get('P08_EXPORT_DIR', 'p08-export'))
files = {'bf16': ROOT / 'gguf-cwe-bf16-evaluation.json', 'q4': ROOT / 'gguf-cwe-evaluation.json'}
data = {name: json.loads(path.read_text(encoding='utf-8')) for name, path in files.items()}
bf, q4 = data['bf16'], data['q4']
if bf['variant'] != 'bf16' or q4['variant'] != 'q4': raise ValueError('Variantes incorrectas')
if bf['n'] != q4['n'] or [r['id'] for r in bf['rows']] != [r['id'] for r in q4['rows']]:
    raise ValueError('Exámenes desalineados')
keys = ('script_sha256', 'reference_sha256', 'tasks_sha256', 'server_sha256', 'n_predict', 'temperature',
        'repeat_penalty', 'repeat_last_n', 'cache_prompt', 'gpu_layers', 'threads')
if any(bf['evaluation_manifest'][key] != q4['evaluation_manifest'][key] for key in keys):
    raise ValueError('Protocolos GGUF distintos')
difference = np.array([q['correcto'] - b['correcto'] for b, q in zip(bf['rows'], q4['rows'])], float)
if not len(difference): raise ValueError('Sin preguntas para comparar')
rng = np.random.default_rng(0)
indices = rng.integers(0, len(difference), (10000, len(difference)))
ci = np.percentile(difference[indices].mean(1), [2.5, 97.5]).tolist()
margin = 0.05
output = {'n': len(difference), 'bf16_sha256': bf['gguf_sha256'], 'q4_sha256': q4['gguf_sha256'],
          'inputs_sha256': {name: hashlib.sha256(path.read_bytes()).hexdigest() for name, path in files.items()},
          'delta_q4_menos_bf16': float(difference.mean()), 'intervalo_pareado_95': ci,
          'q4_acierta_bf16_falla': int((difference > 0).sum()), 'bf16_acierta_q4_falla': int((difference < 0).sum()),
          'margen_practico_prefijado': margin, 'equivalencia_demostrada': bool(ci[0] > -margin and ci[1] < margin),
          'note': 'Mismo servidor CPU, plantilla y preguntas; el intervalo es pareado y no implica equivalencia fuera del margen.'}
destination = ROOT / 'gguf-cwe-bf16-vs-q4.json'
if destination.exists(): raise FileExistsError(destination)
tmp = destination.with_suffix('.json.tmp')
with tmp.open('w', encoding='utf-8') as f:
    json.dump(output, f, ensure_ascii=False, indent=2); f.flush(); os.fsync(f.fileno())
os.replace(tmp, destination)
print('Comparación BF16/Q4 guardada:', destination, flush=True)
