#!/usr/bin/env python3
"""Eröffnungskurse mit Stockfish prüfen – jeden Ast, nicht nur Stichproben.

Meldet:
- Kurszüge der lernenden Seite, die deutlich schlechter sind als Stockfishs bester Zug
  (außer mit [%bewusst] im Kommentar: einfacher für Kinder, obwohl nicht der beste),
- grobe Fehler der Gegenseite (manchmal Absicht – dann sollte es im Kommentar stehen),
- Linienenden, an denen die lernende Seite schlechter steht,
- Züge mit mehr als drei „Warum?“-Fragen (opening.MAX_DEMOS) und doppelte Fragen,
- Pfeile, deren Weg durch eine eigene Figur führt (zum Ansehen: Abzugsangriff, Plan oder Fehler),
- und den Bewertungsverlauf jeder „Warum?“-Vorführung zum Gegenlesen.

Bewertungen werden zwischengespeichert (~/.cache/schach/kurse_pruefen.json), ein zweiter
Lauf nach kleinen Änderungen ist also schnell.

    python tools/kurse_pruefen.py                 # alle Kurse
    python tools/kurse_pruefen.py schach/kurse/london.pgn --depth 20
"""

import argparse
import glob
import json
import os
import sys

import chess
import chess.engine
import chess.pgn

sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
from schach import opening  # noqa: E402

CACHE = os.path.expanduser("~/.cache/schach/kurse_pruefen.json")
LEARNER_LOSS = 70  # Centipawns: so viel schlechter als der beste Zug ist bei eigenen Kurszügen verdächtig
OPPONENT_LOSS = 200  # grober Fehler der Gegenseite
LINE_END = -80  # Linienende: so schlecht darf es höchstens stehen (Skandinavisch steht von Haus aus um -0,6)
MATE = 10000


class Evaluator:
    def __init__(self, depth, threads):
        self.depth = depth
        self.engine = chess.engine.SimpleEngine.popen_uci("stockfish")
        self.engine.configure({"Threads": threads, "Hash": 256})
        self.cache = {}
        if os.path.exists(CACHE):
            try:
                with open(CACHE) as fh:
                    self.cache = json.load(fh)
            except (OSError, ValueError):
                self.cache = {}

    def score(self, board):
        """(Centipawns aus Sicht von Weiß, bester Zug als UCI oder None)."""
        if board.is_game_over():
            outcome = board.outcome()
            if outcome.winner is None:
                return 0, None
            return (MATE if outcome.winner == chess.WHITE else -MATE), None
        key = f"{board.fen()}|{self.depth}"
        if key not in self.cache:
            info = self.engine.analyse(board, chess.engine.Limit(depth=self.depth))
            cp = info["score"].white().score(mate_score=MATE)
            best = info["pv"][0].uci() if info.get("pv") else None
            self.cache[key] = [cp, best]
        cp, best = self.cache[key]
        return cp, best

    def close(self):
        self.engine.quit()
        os.makedirs(os.path.dirname(CACHE), exist_ok=True)
        with open(CACHE, "w") as fh:
            json.dump(self.cache, fh)


def pov(cp, color):
    return cp if color == chess.WHITE else -cp


def fmt(cp):
    if abs(cp) >= MATE - 100:
        return "Matt" if cp > 0 else "-Matt"
    return f"{cp / 100:+.2f}"


def label(board, move):
    number = f"{board.fullmove_number}." if board.turn == chess.WHITE else f"{board.fullmove_number}…"
    return f"{number}{board.san(move)}"


def path_of(board, node):
    moves = []
    while node.parent is not None:
        moves.append(node)
        node = node.parent
    out, b = [], node.board()
    for n in reversed(moves):
        out.append(label(b, n.move))
        b.push(n.move)
    return " ".join(out)


def blocked_arrows(board, node):
    """Pfeile von Läufer/Turm/Dame/Bauer, deren Weg durch eine eigene Figur versperrt ist.

    Gegnerische Figuren dazwischen sind erlaubt: So zeichnet man Fesselungen (Lc4 durch Sd5 auf Ke6).
    """
    problems = []
    for arrow in node.arrows():
        tail, head = arrow.tail, arrow.head
        if tail == head:
            continue
        piece = board.piece_at(tail)
        if piece is None or piece.piece_type in (chess.KNIGHT, chess.KING):
            continue
        between = chess.SquareSet(chess.between(tail, head))
        if not between and chess.square_distance(tail, head) > 1:
            continue  # keine Linie (z. B. Plan-Pfeil) – nicht prüfbar
        blockers = [chess.square_name(s) for s in between
                    if board.piece_at(s) and board.piece_at(s).color == piece.color]
        if blockers:
            problems.append(f"{chess.square_name(tail)}→{chess.square_name(head)} versperrt auf {', '.join(blockers)}")
    return problems


def check_course(path, ev):
    with open(path) as fh:
        game = chess.pgn.read_game(fh)
    color = chess.BLACK if game.headers.get("SchachColor", "white").lower() == "black" else chess.WHITE
    title = game.headers.get("Event", path)
    findings, demos, arrows = [], [], []

    def walk(node, in_demo, demo_log):
        board = node.board()
        for problem in blocked_arrows(board, node):
            arrows.append(f"{path_of(board, node) or 'Start'}: {problem}")
        children = node.variations
        if not children and not in_demo:
            cp, _ = ev.score(board)
            if pov(cp, color) < LINE_END:
                findings.append(f"Linienende: {path_of(board, node)} → {fmt(pov(cp, color))} für die lernende Seite")
        for index, child in enumerate(children):
            demo = in_demo or (index > 0 and "[%warum" in child.comment)
            if demo and not in_demo:
                log = []
                demos.append((path_of(board, node) or "Start", opening.clean_comment(child.comment)[:70], log))
            else:
                log = demo_log
            after = child.board()
            cp_after, _ = ev.score(after)
            if demo:
                log.append(f"{label(board, child.move)} {fmt(cp_after)}")
            else:
                cp_before, best = ev.score(board)
                mover = board.turn
                loss = pov(cp_before, mover) - pov(cp_after, mover)
                best_san = board.san(chess.Move.from_uci(best)) if best else "?"
                where = path_of(after, child)
                if (mover == color and loss > LEARNER_LOSS and child.move.uci() != best
                        and "[%bewusst" not in child.comment):
                    findings.append(f"Kurszug: {where} verliert {loss / 100:.2f} (besser {best_san}, danach {fmt(cp_after)})")
                elif mover != color and loss > OPPONENT_LOSS:
                    # erklärt im eigenen Kommentar oder in der Antwort darauf? Dann ist es Absicht.
                    replies = [opening.clean_comment(r.comment) for r in child.variations[:1]]
                    if not opening.clean_comment(child.comment) and not any(replies):
                        findings.append(f"Gegnerfehler ohne Erklärung: {where} (−{loss / 100:.2f})")
            walk(child, demo, log)

    walk(game, False, None)
    with open(path) as fh:
        course = opening.parse_course(fh.read(), path)
    for (position, move), group in course.demos.items():
        board = chess.Board(group[0].start_fen)
        san = board.san(move)
        titles = [d.title or f"Warum {san}?" for d in group]
        if len(group) > opening.MAX_DEMOS:
            findings.append(f"Zu viele Fragen zu {san} nach {group[0].start_fen}: {len(group)} (höchstens "
                            f"{opening.MAX_DEMOS})")
        if len(set(titles)) < len(titles):
            findings.append(f"Gleiche Frage doppelt zu {san} nach {group[0].start_fen}: {titles}")
    return title, findings, demos, arrows


def main():
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    parser.add_argument("paths", nargs="*")
    parser.add_argument("--depth", type=int, default=18)
    parser.add_argument("--threads", type=int, default=4)
    args = parser.parse_args()
    paths = args.paths or sorted(glob.glob(os.path.join(opening.COURSE_DIR, "*.pgn")))
    ev = Evaluator(args.depth, args.threads)
    total = 0
    try:
        for path in paths:
            title, findings, demos, arrows = check_course(path, ev)
            total += len(findings)
            print(f"\n=== {title} ({os.path.basename(path)}) – {len(findings)} Befund(e)")
            for finding in findings:
                print("  •", finding)
            for arrow in arrows:
                # Abzugsangriff (Ld2 hinter Sc3) oder Plan (De2 hinter e3, vor e3–e4) – oder ein Fehler
                print("  ? Pfeil hinter eigener Figur, bitte ansehen:", arrow)
            for where, text, log in demos:
                print(f"  ▸ Vorführung nach {where}: „{text}“")
                print("      " + " ".join(log))
    finally:
        ev.close()
    print(f"\n{total} Befund(e) insgesamt.")
    return 1 if total else 0


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