"""Juez local sobre pares de variantes ya fijadas y examen CWE, sin etiquetas humanas."""
import json
import os
import hashlib
import re
import urllib.request
import urllib.parse
from itertools import combinations
from pathlib import Path

import numpy as np
from sklearn.linear_model import LogisticRegression
from transformers import AutoTokenizer

MODEL = 'qwen2.5-7b-instruct-q4_k_m-00001-of-00002.gguf'
REV = 'bb5d59e06d9551d752d08b292a50eb208b07ab1f'
SHARDS = ['dfce12e3862a5283ccfb88221b48480e58745165de856439950d0f22590580db',
          '539cf93f78e887edea1c04e2d7d8cdaca9d01dae9c9025bcb8accbe29df3d72a']
SERVER = os.environ.get('P08_JUDGE_URL', 'http://127.0.0.1:11441/v1/chat/completions')
ROOT = Path(os.environ.get('P08_FINAL_DIR', 'p08-final'))
SFT = Path(os.environ['P08_L04_DIR'])
NAMES = ('base', 'sft', 'dpo', 'grpo')
data = {v: json.loads((ROOT / f'{v}.json').read_text(encoding='utf-8')) for v in NAMES}
questions = json.loads((SFT / 'test.json').read_text(encoding='utf-8'))
ids = [r['id'] for r in questions]
for name in NAMES:
    if [r['id'] for r in data[name]['results']['cwe']] != ids:
        raise ValueError('Las preguntas no están alineadas')
tok = None

def verify_judge_server():
    """Vincula la respuesta del servidor local con los dos archivos reales."""
    endpoint = urllib.parse.urlsplit(SERVER)
    if endpoint.hostname not in ('localhost', '127.0.0.1', '::1'):
        raise ValueError('La comprobación de archivos exige un servidor local')
    props_url = urllib.parse.urlunsplit((endpoint.scheme, endpoint.netloc, '/props', '', ''))
    with urllib.request.urlopen(props_url, timeout=10) as response:
        props = json.load(response)
    first = Path(props['model_path'])
    if props.get('model_alias') != MODEL or first.name != MODEL:
        raise ValueError('El servidor no identifica el modelo fijado')
    second = first.with_name(first.name.replace('-00001-of-00002.gguf', '-00002-of-00002.gguf'))
    for path, expected in zip((first, second), SHARDS):
        h = hashlib.sha256()
        with path.open('rb') as stream:
            for chunk in iter(lambda: stream.read(8 * 1024 * 1024), b''):
                h.update(chunk)
        if h.hexdigest() != expected:
            raise ValueError(f'La huella del modelo servido no coincide: {path.name}')
    return {'model_path': str(first), 'template_sha256': hashlib.sha256(
        str(props.get('chat_template')).encode('utf-8')).hexdigest()}


def atomic_json(path, value):
    temporary = path.with_suffix(path.suffix + '.tmp')
    with temporary.open('w', encoding='utf-8') as file:
        json.dump(value, file, ensure_ascii=False)
        file.flush(); os.fsync(file.fileno())
    os.replace(temporary, path)

def judge(prompt, first, second):
    content = (prompt + '\n\nCompare two candidate answers. Which is more correct? '
               'Reply with only A or B.\nA: ' + first + '\nB: ' + second)
    data = json.dumps({'model': MODEL, 'messages': [{'role': 'user', 'content': content}],
                       'temperature': 0, 'max_tokens': 4}).encode('utf-8')
    req = urllib.request.Request(SERVER, data=data, headers={'Content-Type': 'application/json'})
    with urllib.request.urlopen(req, timeout=600) as response:
        payload = json.load(response)
    if payload.get('model') != MODEL:
        raise ValueError('El servidor respondió con un identificador de modelo distinto')
    text = payload['choices'][0]['message']['content'].strip()
    return text, text.upper() if re.fullmatch(r'[AB]', text, re.IGNORECASE) else None

def summarize(rows):
    valid = [row for row in rows if row['win'] is not None]
    rng = np.random.default_rng(0)
    wins = np.array([row['win'] for row in valid], dtype=float)
    if len(wins):
        boot = wins[rng.integers(0, len(wins), (10000, len(wins)))].mean(1)
        raw_ci = np.percentile(boot, [2.5, 97.5]).tolist()
    else: raw_ci = None
    # Los empates no determinan una etiqueta binaria para la regresión.
    binary = [row for row in valid if row['win'] in (0, 1)]
    controlled = None
    if len(binary) >= 4 and len({row['win'] for row in binary}) == 2:
        x = np.array([row['length_difference'] for row in binary], float)[:, None]
        y = np.array([row['win'] for row in binary], int)
        fitted = LogisticRegression(C=1.0).fit(x, y)
        boots = []
        for _ in range(1000):
            idx = rng.integers(0, len(y), len(y))
            if len(np.unique(y[idx])) < 2: continue
            boots.append(float(LogisticRegression(C=1.0).fit(x[idx], y[idx]).predict_proba([[0.]])[0, 1]))
        controlled = {'value': float(fitted.predict_proba([[0.]])[0, 1]),
            'ci95': np.percentile(boots, [2.5, 97.5]).tolist() if len(boots) >= 500 else None,
            'bootstrap_valid': len(boots), 'n_binary': len(binary), 'range': [float(x.min()), float(x.max())],
            'extrapolated_to_zero': bool(not (x.min() <= 0 <= x.max())), 'method': 'logistic L2 C=1'}
    comparable = [row for row in valid if row['verified_difference'] != 0 and row['win'] in (0, 1)]
    agreement = float(np.mean([row['win'] == (row['verified_difference'] > 0) for row in comparable])) if comparable else None
    return {'raw': float(wins.mean()) if len(wins) else None, 'raw_ci95': raw_ci,
        'resolved': len(valid), 'unresolved': len(rows) - len(valid), 'total': len(rows),
        'controlled': controlled, 'verified_comparable': len(comparable), 'verified_agreement': agreement}

def main():
    global tok
    result_path = ROOT / 'judge-final.json'
    if result_path.exists(): raise FileExistsError('El informe de juez existe; no se sobrescribe')
    verified_server = verify_judge_server()
    manifest = {'model': MODEL, 'revision': REV, 'shards_sha256': SHARDS, 'server_version': 'llama.cpp b9354',
        'server_verified': verified_server,
        'length_tokenizer': 'Qwen/Qwen2.5-0.5B-Instruct', 'length_tokenizer_revision': '7ae557604adf67be50417f59c2c2f167def9a775',
        'script_sha256': hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
        'inputs_sha256': {v: hashlib.sha256((ROOT / f'{v}.json').read_bytes()).hexdigest() for v in NAMES},
        'questions_sha256': hashlib.sha256((SFT / 'test.json').read_bytes()).hexdigest()}
    manifest_path = ROOT / 'judge-manifest.json'
    if manifest_path.exists() and json.loads(manifest_path.read_text(encoding='utf-8')) != manifest:
        raise ValueError('Cambió el protocolo o alguna entrada del juez')
    manifest_path.write_text(json.dumps(manifest, ensure_ascii=False, indent=2), encoding='utf-8')
    tok = AutoTokenizer.from_pretrained('Qwen/Qwen2.5-0.5B-Instruct',
        revision='7ae557604adf67be50417f59c2c2f167def9a775', local_files_only=True)
    results = {}
    for a, b in combinations(NAMES, 2):
        pair_path = ROOT / f'judge-{b}-{a}.json'
        if pair_path.exists():
            results[f'{b}-{a}'] = json.loads(pair_path.read_text(encoding='utf-8'))
            continue
        partial = ROOT / f'judge-{b}-{a}.jsonl'
        rows = []
        if partial.exists():
            with partial.open(encoding='utf-8') as file:
                for line in file:
                    if not line.endswith('\n'):
                        raise ValueError('El parcial del juez termina con una línea incompleta')
                    rows.append(json.loads(line))
        if len(rows) > len(questions) or any(row['id'] != ids[i] for i, row in enumerate(rows)):
            raise ValueError('El parcial del juez no coincide con el examen')
        left, right = data[a]['results']['cwe'], data[b]['results']['cwe']
        for i in range(len(rows), len(questions)):
            question, x, y = questions[i], left[i], right[i]
            if x['salida'] == y['salida']:
                forward = reverse = None; outcome = 0.5
            else:
                forward, p = judge(question['prompt'], x['salida'], y['salida'])
                reverse, q = judge(question['prompt'], y['salida'], x['salida'])
                outcome = int(p == 'B') if p and q and (p == 'B') == (q == 'A') else None
            row = {'id': question['id'], 'win': outcome, 'forward': forward, 'reverse': reverse,
                'length_difference': len(tok.encode(y['salida'], add_special_tokens=False)) - len(tok.encode(x['salida'], add_special_tokens=False)),
                'verified_difference': y['correcto'] - x['correcto']}
            with partial.open('a', encoding='utf-8') as file:
                file.write(json.dumps(row, ensure_ascii=False) + '\n'); file.flush(); os.fsync(file.fileno())
            rows.append(row)
            if i % 25 == 0: print(b, 'frente a', a, i, '/', len(questions), flush=True)
        results[f'{b}-{a}'] = {**summarize(rows), 'rows': rows}
        # Guardado incremental por pareja, sin tratar un fichero parcial como informe completo.
        atomic_json(pair_path, results[f'{b}-{a}'])
    atomic_json(result_path, {'manifest': manifest, 'results': results})
    print('Juez final:', result_path, flush=True)

if __name__ == '__main__': main()
