"""Vergleich: Maia-3 im Original (PyTorch, maia3) gegen den ONNX-Export (schach.maia_onnx).

Stellungen: alle Kurslinien aus schach/kurse plus Partien, die Maia (PyTorch) gegen sich
selbst spielt (bis ins Endspiel). Für jede Stellung und mehrere Elo-Stufen werden die vollen
Zugverteilungen verglichen: Top-1 gleich, Top-5 gleich (als Menge und Reihenfolge),
größte Abweichung einer Zugwahrscheinlichkeit und der WDL-Werte.

Braucht maia3 + PyTorch (nur auf dem Entwicklerrechner):

    python tools/maia_onnx_vergleich.py [--games 6] [--seed 1]
"""

import argparse
import glob
import os
import random
import sys
from collections import deque

import chess
import chess.pgn
import numpy as np
import torch

sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))

from maia3.dataset import get_historical_tokens, get_legal_moves_mask, tokenize_board  # noqa: E402
from maia3.model_registry import apply_model_config, resolve_checkpoint_path, resolve_model_spec  # noqa: E402
from maia3.uci import load_model, parse_args  # noqa: E402
from maia3.utils import get_all_possible_moves  # noqa: E402

from schach import maia_onnx  # noqa: E402

ELOS = [(1100, 1100), (1500, 1500), (1900, 1900), (2300, 2300), (1200, 2000)]


class Torch:
    def __init__(self):
        device = "cuda" if torch.cuda.is_available() else "cpu"  # Referenz rechnet in fp32, auch auf der GPU
        cfg = parse_args(["--model", "79m", "--use-uci-history", "--device", device, "--no-use-amp"])
        spec = resolve_model_spec("79m")
        apply_model_config(cfg, spec)
        cfg.checkpoint_path = resolve_checkpoint_path(spec, local_files_only=True)
        self.cfg = cfg
        self.model = load_model(cfg)
        self.index = {m: i for i, m in enumerate(get_all_possible_moves())}
        assert get_all_possible_moves() == maia_onnx.ALL_MOVES, "Zugvokabular weicht ab"

    @torch.no_grad()
    def policy(self, boards, self_elo, oppo_elo):
        """boards: Stellungen der Partie bis jetzt (älteste zuerst) → (Wahrscheinlichkeiten, WDL-Logits)."""
        history = deque((tokenize_board(b) for b in boards[-8:]), maxlen=8)
        tokens = get_historical_tokens(history, self.cfg, 0.0, 0.0, 0.0, 0.0).unsqueeze(0)
        dev = self.cfg.device
        logits, value, _ = self.model(tokens.to(dev), torch.tensor([self_elo], device=dev),
                                      torch.tensor([oppo_elo], device=dev))
        logits, value = logits.cpu(), value.cpu()
        mask = get_legal_moves_mask(boards[-1], self.index)
        logits = logits[0].float().masked_fill(~mask, float("-inf"))
        return torch.softmax(logits, -1).double().numpy(), value[0].double().numpy()


class Onnx:
    def __init__(self, path=None):
        self.model = maia_onnx.Model(path or maia_onnx.model_path())

    def policy(self, boards, self_elo, oppo_elo):
        history = deque((maia_onnx.tokenize(b) for b in boards[-8:]), maxlen=8)
        logits, value = self.model.run([history], [self_elo], [oppo_elo])
        legal = maia_onnx.legal_index(boards[-1])
        full = np.full(len(maia_onnx.ALL_MOVES), -np.inf)
        idx = np.fromiter(legal, dtype=np.int64)
        full[idx] = logits[0, idx]
        return maia_onnx._softmax(full), value[0].astype(np.float64)


def course_lines():
    """Jede Kurslinie als Zugfolge (Hauptvariante und alle Varianten bis zum Blatt)."""
    lines = []
    for path in sorted(glob.glob(os.path.join(os.path.dirname(__file__), "..", "schach", "kurse", "*.pgn"))):
        with open(path, encoding="utf-8") as fh:
            while (game := chess.pgn.read_game(fh)) is not None:
                stack = [(game, [])]
                while stack:
                    node, moves = stack.pop()
                    if not node.variations:
                        lines.append(moves)
                    for child in node.variations:
                        stack.append((child, moves + [child.move]))
    return lines


def selfplay(torch_model, rng, count):
    games = []
    for _ in range(count):
        board, moves = chess.Board(), []
        elo = rng.choice([1100, 1500, 1900, 2300])
        while not board.is_game_over() and len(moves) < 160:
            boards = _boards(moves)
            probs, _ = torch_model.policy(boards, elo, elo)
            idx = rng.choices(range(len(probs)), weights=probs.tolist())[0]
            move = maia_onnx.legal_index(board)[idx]
            board.push(move)
            moves.append(move)
        games.append(moves)
    return games


def _boards(moves):
    board = chess.Board()
    boards = [board.copy()]
    for move in moves:
        board.push(move)
        boards.append(board.copy())
    return boards


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--games", type=int, default=6, help="Selbstspiel-Partien zusätzlich zu den Kursen")
    parser.add_argument("--seed", type=int, default=1)
    parser.add_argument("--every", type=int, default=3, help="nur jede n-te Stellung einer Partie prüfen")
    parser.add_argument("--model-path", help="ONNX-Datei statt der, die schach.maia_onnx wählt")
    args = parser.parse_args()
    rng = random.Random(args.seed)

    ref, onnx = Torch(), Onnx(args.model_path)
    print("ONNX-Modell:", args.model_path or maia_onnx.model_path())
    sequences = course_lines() + selfplay(ref, rng, args.games)

    seen, stats = set(), dict(n=0, top1=0, top5set=0, top5order=0)
    worst_p, worst_wdl, misses = 0.0, 0.0, []
    for moves in sequences:
        boards = _boards(moves)
        for ply in range(0, len(boards), args.every):
            prefix = boards[:ply + 1]
            key = tuple(m.uci() for m in moves[:ply])
            if key in seen or prefix[-1].is_game_over():
                continue
            seen.add(key)
            for self_elo, oppo_elo in ELOS:
                p_ref, v_ref = ref.policy(prefix, self_elo, oppo_elo)
                p_onx, v_onx = onnx.policy(prefix, self_elo, oppo_elo)
                top_ref = list(np.argsort(-p_ref, kind="stable")[:5])
                top_onx = list(np.argsort(-p_onx, kind="stable")[:5])
                stats["n"] += 1
                stats["top1"] += top_ref[0] == top_onx[0]
                stats["top5set"] += set(top_ref) == set(top_onx)
                stats["top5order"] += top_ref == top_onx
                worst_p = max(worst_p, float(np.max(np.abs(p_ref - p_onx))))
                wdl_ref = torch.softmax(torch.tensor(v_ref), -1).numpy()
                wdl_onx = maia_onnx._softmax(v_onx)
                worst_wdl = max(worst_wdl, float(np.max(np.abs(wdl_ref - wdl_onx))))
                if top_ref[0] != top_onx[0]:
                    misses.append((prefix[-1].fen(), self_elo, oppo_elo,
                                   float(p_ref[top_ref[0]]), float(p_ref[top_onx[0]])))

    n = stats["n"]
    print(f"Stellungen × Elo-Stufen: {n} ({len(seen)} Stellungen)")
    print(f"Top-1 gleich:            {stats['top1']}/{n}")
    print(f"Top-5 gleiche Menge:     {stats['top5set']}/{n}")
    print(f"Top-5 gleiche Reihenfolge: {stats['top5order']}/{n}")
    print(f"größte Abweichung Zugwahrscheinlichkeit: {worst_p:.2e}")
    print(f"größte Abweichung WDL:                   {worst_wdl:.2e}")
    for fen, se, oe, p1, p2 in misses[:10]:
        print(f"  Top-1 anders: {fen} (Elo {se}/{oe}): PyTorch {p1:.4f} vs. ONNX-Wahl {p2:.4f}")
    return 0 if stats["top1"] == n else 1


if __name__ == "__main__":
    sys.exit(main())
