"""„Warum nicht?“ und die dritte Hinweisstufe als Nebenvarianten im Partiebaum (Analysebrett,
Stufe 5): mit den echten Mixins, ohne Engine (die Erklärungsbäume sind von Hand gebaut)."""

import unittest

import chess
import chess.pgn

from schach import explain, savegames, zustand
from tests.test_zustand_regression import FakeWindow, played


def m(uci):
    return chess.Move.from_uci(uci)


def why_not(board, ply, best, refutation=()):
    """Baum wie explain.why_not_job(variation=True): gespielter Zug mit Widerlegung, bester Zug daneben."""
    before = board.root()
    for move in board.move_stack[:ply]:
        before.push(move)
    tree = explain.line(before, [board.move_stack[ply], *refutation])
    tree.info(tree.first())["label"] = "Gespielt"
    top = tree.game.add_variation(best, comment="Besser als … Damit gewinnst du.")
    tree.info(top)["label"] = "Bester Zug"
    return tree


class Window(FakeWindow):
    def __init__(self, *sans):
        super().__init__(played(*sans), mode="maia")
        self.saved = 0

    def _schedule_autosave(self):
        self.saved += 1


class WhyNotTest(unittest.TestCase):
    def setUp(self):
        self.win = Window("e4", "e5", "Ke2", "d6")
        self.tree = why_not(self.win.board, 2, m("g1f3"), refutation=[m("d8g5")])

    def test_best_move_hangs_before_the_played_move(self):
        win = self.win
        win._why_not_variation(2, self.tree)
        fork = win._game_node(1)
        self.assertEqual([(c.move, c.starting_comment) for c in fork.variations],
                         [(m("e1e2"), ""), (m("g1f3"), "Bester Zug")])
        self.assertEqual(win.game_tree.label(fork.variations[1]), "Bester Zug")
        self.assertTrue(win._why_not_known(2))

    def test_board_jumps_to_the_fork(self):
        win = self.win
        win._why_not_variation(2, self.tree)
        self.assertTrue(win.demo["game"])
        self.assertIs(win.demo["node"], win._game_node(1))
        self.assertIsNotNone(win.paused)  # das Analysebrett hält Maia an
        self.assertEqual(zustand.violations(win), [])

    def test_refutation_hangs_after_the_played_move(self):
        win = self.win
        win._why_not_variation(2, self.tree)
        after = win._game_node(2)
        self.assertEqual([(c.move, c.starting_comment) for c in after.variations],
                         [(m("d7d6"), ""), (m("d8g5"), "Warum nicht 2. Ke2?")])

    def test_widerlegung_die_der_partie_folgt_traegt_den_erklaerten_zug(self):
        """Nutzerbericht 24.11.2026: Folgt die Widerlegung der Partie zwei Züge und zweigt erst dann
        ab, steht sie unter einem Zug des Gegners. Ohne Zug im Namen sah „Warum nicht?“ dort aus,
        als ginge es um den Zug des Gegners."""
        win = Window("e4", "e5", "Ke2", "d6", "d3", "Nc6")
        tree = why_not(win.board, 2, m("g1f3"), refutation=[m("d7d6"), m("d2d3"), m("d8g5")])
        win._why_not_variation(2, tree)
        deeper = win._game_node(4).variations  # nach 3. d3: Partie 3… Sc6, Widerlegung 3… Dg5
        self.assertEqual([(c.move, c.starting_comment) for c in deeper],
                         [(m("b8c6"), ""), (m("d8g5"), "Warum nicht 2. Ke2?")])

    def test_twice_adds_nothing(self):
        win = self.win
        win._why_not_variation(2, self.tree)
        win._why_not_variation(2, self.tree)
        self.assertEqual(len(win._game_node(1).variations), 2)
        self.assertEqual(len(win._game_node(2).variations), 2)

    def test_saved_with_the_game(self):
        win = self.win
        win._why_not_variation(2, self.tree)
        self.assertGreater(win.saved, 0)
        state = savegames.GameState(board=win.board, human=win.human, elo=1500,
                                    variations=win._game_variations())
        loaded = savegames.from_pgn(savegames.to_pgn(state))
        self.assertEqual([v[0] for v in loaded.variations[1]], [m("g1f3")])
        self.assertEqual(loaded.variations[1][0][4], "Bester Zug")


class HintTest(unittest.TestCase):
    def setUp(self):
        self.win = Window("e4", "e5", "Nf3", "Nc6")
        board = self.win.board.copy()
        self.tree = explain.line(board, [m("f1c4"), m("g8f6")])
        self.tree.first().comment = "Du entwickelst eine Figur."

    def test_hint_hangs_at_the_present_and_board_shows_it(self):
        win = self.win
        win._hint_variation(self.tree)
        present = win._game_node(3)
        hint = present.variations[0]
        self.assertEqual((hint.move, hint.starting_comment), (m("f1c4"), "Hinweis 3. Lc4"))
        self.assertEqual(win.game_tree.label(hint), "Hinweis")  # Schild am Pfeil bleibt kurz
        self.assertIs(win.demo["node"], hint)
        self.assertEqual(zustand.violations(win), [])

    def test_playing_the_hint_makes_it_the_played_move(self):
        win = self.win
        win._hint_variation(self.tree)
        hint = win._game_node(3).variations[0]
        win.demo = None
        win.paused = None
        win.board.push(m("f1c4"))
        win._game_tree()
        self.assertIs(win._game_node(4), hint)  # derselbe Knoten, jetzt gespielt
        self.assertTrue(win.game_tree.meta[hint]["played"])
        self.assertEqual([c.move for c in hint.variations], [m("g8f6")])  # Rest bleibt Nebenvariante

    def test_another_move_keeps_the_hint_as_side_line(self):
        win = self.win
        win._hint_variation(self.tree)
        win.demo = None
        win.paused = None
        win.board.push(m("f1b5"))
        win._game_tree()
        present = win._game_node(3)
        self.assertEqual([c.move for c in present.variations], [m("f1b5"), m("f1c4")])
        self.assertEqual(present.variations[1].starting_comment, "Hinweis 3. Lc4")


if __name__ == "__main__":
    unittest.main()
