import shutil
import unittest

import chess
import chess.engine
import chess.pgn

from schach import explain


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


class DescribeTest(unittest.TestCase):
    def test_knight_fork_on_king_and_rook(self):
        board = chess.Board("r3k3/8/8/8/8/8/3N4/4K3 w - - 0 1")
        sentences, shapes = explain.describe(board, m("d2c4"), chess.WHITE)
        self.assertFalse(any("Gabel" in s for s in sentences))  # c4 greift nichts an
        board = chess.Board("r3k3/8/8/3N4/8/8/8/4K3 w - - 0 1")
        sentences, shapes = explain.describe(board, m("d5c7"), chess.WHITE)
        self.assertTrue(any(s.startswith("Gabel: Der Springer") for s in sentences), sentences)
        self.assertIn("Schach!", sentences)
        self.assertEqual({s[0] for s in shapes}, {chess.E8, chess.A8})

    def test_capture_names_victim(self):
        board = chess.Board("4k3/8/8/3q4/8/2N5/8/4K3 w - - 0 1")
        sentences, _ = explain.describe(board, m("c3d5"), chess.WHITE)
        self.assertEqual(sentences[0], "Du schlägst die Dame auf d5.")

    def test_opponent_capture_uses_color(self):
        board = chess.Board("4k3/8/8/3q4/8/2N5/8/4K3 b - - 0 1")
        sentences, _ = explain.describe(board, m("d5c3"), chess.WHITE)
        self.assertEqual(sentences[0], "Schwarz schlägt den Springer auf c3.")

    def test_pin_against_king(self):
        board = chess.Board("4k3/8/2n5/8/8/8/8/4KB2 w - - 0 1")
        sentences, shapes = explain.describe(board, m("f1b5"), chess.WHITE)
        self.assertTrue(any(s.startswith("Fesselung: Der Springer auf c6") for s in sentences), sentences)
        self.assertIn((chess.C6, chess.C6, "red"), shapes)

    def test_mate(self):
        board = chess.Board("6k1/5ppp/8/8/8/8/8/R5K1 w - - 0 1")
        sentences, _ = explain.describe(board, m("a1a8"), chess.WHITE)
        self.assertEqual(sentences, ["Schachmatt!"])


class TrimTest(unittest.TestCase):
    def test_attack_with_checks_runs_on(self):
        board = chess.Board()
        for san in "e4 g6 Nf3 g5 h3 f6".split():
            board.push_san(san)
        pv = [m(u) for u in "f3g5 e7e6 d1h5 e8e7 h5f7 e7d6 g5h7 f8h6".split()]
        self.assertEqual(explain.trim(board, pv), pv[:7])  # bis Sxh7, nicht schon nach Sxg5 e6

    def test_stops_after_exchange_settles(self):
        # Sxd5, danach ruhige Züge: nach der Antwort ist der Gewinn eingefahren
        board = chess.Board("4k3/8/8/3q4/8/2N5/8/4K3 w - - 0 1")
        pv = [m("c3d5"), m("e8d7"), m("d5f4"), m("d7d6"), m("e1e2"), m("d6d5")]
        self.assertEqual(explain.trim(board, pv), pv[:2])

    def test_quiet_line_is_short(self):
        board = chess.Board()
        pv = [m(u) for u in ("e2e4", "e7e5", "g1f3", "b8c6", "f1b5", "a7a6", "b5a4")]
        self.assertEqual(len(explain.trim(board, pv)), explain.QUIET_PLIES)

    def test_line_goes_on_to_mate_after_exchange(self):
        # 10. dxe4 Sxe4 11. Dd8#: nach dem Tausch kommt noch das Matt
        board = chess.Board(AFTER_DXE4)
        pv = [m("d3e4"), m("f6e4"), m("d1d8")]
        self.assertEqual(explain.trim(board, pv), pv)

    def test_mate_ends_line(self):
        board = chess.Board("6k1/5ppp/8/8/8/8/8/R5K1 w - - 0 1")
        self.assertEqual(explain.trim(board, [m("a1a8"), m("g8h8")]), [m("a1a8")])


class BuildStepsTest(unittest.TestCase):
    def test_parried_threat_and_result(self):
        board = chess.Board("4k3/8/8/3q4/8/2N5/8/4K3 w - - 0 1")
        steps = explain.build_steps(board, [m("c3d5"), m("e8d7")])
        self.assertEqual(len(steps), 1)  # Kd7 ist ruhig: nur Sxd5 mit Ergebnis
        self.assertIn("Ergebnis: Du gewinnst die Dame.", steps[-1][1])

    def test_threat_mentioned_when_not_replayed(self):
        board = chess.Board("r1bqkbnr/pppp1ppp/2n5/4p2Q/2B1P3/8/PPPP1PPP/RNB1K1NR b KQkq - 3 3")
        steps = explain.build_steps(board, [m("g7g6"), m("h5f3")], threat=m("h5f7"))
        self.assertIn("Das wehrt die Drohung Dxf7# ab.", steps[0][1])
        self.assertIn((chess.H5, chess.F7, "threat"), steps[0][2])

    def test_quiet_continuation_is_dropped(self):
        # Lb3 weicht dem Bauern aus; danach passiert nichts mehr, was zum Zug gehört
        board = chess.Board("rn1qkb1r/5ppp/2pp1n2/1p2p3/2B1P1b1/3P1N2/PPP2PPP/RNBQR1K1 w kq - 0 7")
        pv = [m("c4b3"), m("a7a6"), m("h2h3"), m("g4h5")]
        steps = explain.build_steps(board, pv, threat=m("b5c4"))
        self.assertEqual([s[0] for s in steps], [m("c4b3")])
        self.assertIn("stand in Gefahr", steps[0][1])


AFTER_DXE4 = "rn2kb1r/p4ppp/2p2n2/Bp2p3/4p1b1/1B1P1N2/PPP2PPP/RN1QR1K1 w kq - 0 10"  # vor 10. dxe4


class MateThreatTest(unittest.TestCase):
    def test_missed_mate_threat(self):
        tree = explain.comment(explain.line(chess.Board(AFTER_DXE4), [m("d3e4"), m("f6e4"), m("d1d8")]))
        first = tree.first()
        self.assertIn("Du drohst Dd8#.", first.comment)
        self.assertIn("Das übersieht Dd8#.", first.variations[0].comment)
        self.assertIn((chess.D1, chess.D8, "hint"), tree.shapes(first.variations[0]))

    def test_parried_mate_threat(self):
        tree = explain.comment(explain.line(chess.Board(AFTER_DXE4), [m("d3e4"), m("b8d7")]))
        self.assertIn("Das wehrt Dd8# ab.", tree.first().variations[0].comment)


QUEEN_UP = "4k3/p7/8/3q4/8/2N5/P7/4K3 w - - 0 1"


class FakeEngine:
    """Stockfish-Ersatz: Bewertung je erstem Zug (Weiß, Centipawns), Fortsetzung ein Königszug."""

    def __init__(self, scores, pv):
        self.scores, self.pv = scores, pv

    def analyse(self, board, limit, root_moves=None, multipv=None):
        move = root_moves[0] if root_moves else next(iter(board.legal_moves))
        value = self.scores.get(move.uci(), 0)
        score = chess.engine.Mate(int(value[1:])) if isinstance(value, str) else chess.engine.Cp(value)
        info = {"score": chess.engine.PovScore(score, chess.WHITE),
                "pv": [move] + self.pv.get(move.uci(), [])}
        return [info] if multipv else info


class TreeTest(unittest.TestCase):
    def grow(self, scores):
        engine = FakeEngine(scores, {"c3d5": [m("e8f7")], "e8d7": [m("e1e2")], "e8d8": [m("e1e2")],
                                     "e8f7": [m("e1e2")]})
        maia = lambda board: [(m("e8d7"), 0.6), (m("e8d8"), 0.3), (m("e8f8"), 0.05)]  # noqa: E731
        return explain.grow(chess.Board(QUEEN_UP), m("c3d5"), engine, maia, "Maia 600")

    def test_opponent_fork_from_maia_and_stockfish(self):
        tree = self.grow({"c3d5": 900, "e8d7": 900, "e8d8": 900, "e8f7": 900})
        replies = tree.first().variations
        self.assertEqual([r.move for r in replies], [m("e8d7"), m("e8d8"), m("e8f7")])  # Maia zuerst
        self.assertEqual(tree.label(replies[0]), "Maia 600 · meistens")
        self.assertEqual(tree.label(replies[1]), "Maia 600 · oft")
        self.assertEqual(tree.label(replies[2]), "Bester Zug")
        self.assertEqual(replies[0].variations[0].move, m("e1e2"))  # Hauptlinie geht weiter

    def test_prune_keeps_only_forks_that_matter(self):
        tree = explain.prune(self.grow({"c3d5": 900, "e8d7": 900, "e8d8": 910, "e8f7": 300}))
        replies = tree.first().variations
        self.assertEqual([r.move for r in replies], [m("e8d7"), m("e8f7")])  # d8 ist wie d7: weg

    def test_prune_keeps_fork_between_mate_and_no_mate(self):
        # Gewinnchance 97 % gegen Matt: kaum Abstand in Prozent, aber ein echter Unterschied
        tree = explain.prune(self.grow({"c3d5": 900, "e8d7": "#3", "e8d8": 900, "e8f7": 900}))
        self.assertEqual([r.move for r in tree.first().variations], [m("e8d7"), m("e8d8"), m("e8f7")])

    def test_comment_names_maia_and_best_defence(self):
        tree = explain.comment(explain.prune(self.grow({"c3d5": 900, "e8d7": 900, "e8f7": 300})))
        replies = tree.first().variations
        self.assertIn("So spielt Maia 600 meistens.", replies[0].comment)
        self.assertIn("Die beste Verteidigung.", replies[-1].comment)
        self.assertIn("Ergebnis: Du gewinnst die Dame.", replies[0].comment)

    def test_from_steps_keeps_course_comments(self):
        board = chess.Board()
        tree = explain.from_steps(board.fen(), [(m("e2e4"), "Zentrum", ((12, 28, "green"),)), (m("e7e5"), "", ())])
        self.assertEqual([n.move for n in tree.game.mainline()], [m("e2e4"), m("e7e5")])
        self.assertEqual(tree.first().comment, "Zentrum")
        self.assertEqual(tree.shapes(tree.first()), ((12, 28, "green"),))


class OwnMoveTest(unittest.TestCase):
    def test_opponent_move_is_answered_for_hero(self):
        board = chess.Board(QUEEN_UP.replace(" w ", " b "))
        engine = FakeEngine({"e8d7": 900}, {"e8d7": [m("c3d5")]})
        tree = explain.grow(board, m("e8d7"), engine, hero=chess.WHITE)
        self.assertEqual(tree.hero, chess.WHITE)
        self.assertEqual(tree.first().variations[0].move, m("c3d5"))
        explain.comment(tree)
        self.assertIn("Diesen Zug hast du ausprobiert.", tree.first().comment)
        self.assertIn("Du schlägst die Dame", tree.first().variations[0].comment)

    def test_better_move_is_named(self):
        tree = explain.comment(explain.line(chess.Board(QUEEN_UP), [m("e1e2")]), better=m("c3d5"))
        self.assertIn("Besser war Sxd5.", tree.first().comment)
        self.assertNotIn("besten Zug", tree.first().comment)

    def test_graft_copies_moves_comments_and_meta(self):
        tree = explain.line(chess.Board(QUEEN_UP), [m("c3d5")])
        sub = explain.comment(explain.line(tree.first().board(), [m("e8d7"), m("d5f4")]))
        sub.info(sub.first())["label"] = "Maia 600 · oft"
        child = explain.graft(tree, tree.first(), sub)
        self.assertIs(child, tree.first().variations[0])
        self.assertEqual(child.variations[0].move, m("d5f4"))
        self.assertEqual(tree.label(child), "Maia 600 · oft")
        self.assertEqual(child.comment, sub.first().comment)

    def test_merge_reuses_existing_moves_and_names_new_branches(self):
        # Partie: 1. Sxd5 Kd7, dazu eine Erklärung mit 1. Sxd5 Kd7 2. Sf4 und 1. Sxd5 Ke7
        game = explain.line(chess.Board(QUEEN_UP), [m("c3d5"), m("e8d7")])
        played = game.first()
        game.info(played)["label"] = "Partie"
        played.comment = "gespielt"
        sub = explain.line(chess.Board(QUEEN_UP), [m("c3d5"), m("e8d7"), m("d5f4")])
        sub.first().add_variation(m("e8e7"), comment="auch möglich")
        sub.first().comment = "aus der Erklärung"
        sub.info(sub.first().variations[1])["label"] = "Bester Zug"
        found = explain.merge(game, game.game, sub, sub.game.variations, "Warum nicht?")
        self.assertIs(found[sub.first()], played)  # vorhandener Zug: weiterbenutzt
        self.assertEqual(played.comment, "gespielt")  # … mit seinem Kommentar
        self.assertEqual(game.label(played), "Partie")
        reply = played.variations[0]
        self.assertEqual([c.move for c in reply.variations], [m("d5f4")])
        self.assertEqual(reply.variations[0].starting_comment, "Warum nicht?")  # zweigt an Vorhandenem ab
        side = played.variations[1]
        self.assertEqual((side.move, side.comment, side.starting_comment), (m("e8e7"), "auch möglich", "Warum nicht?"))
        self.assertEqual(game.label(side), "Bester Zug")
        # noch einmal gemischt: nichts doppelt
        explain.merge(game, game.game, sub, sub.game.variations, "Warum nicht?")
        self.assertEqual(len(played.variations), 2)
        self.assertEqual(len(reply.variations), 1)

    def test_merge_names_only_where_the_branch_leaves_the_tree(self):
        game = explain.line(chess.Board(QUEEN_UP), [m("c3d5")])
        sub = explain.line(chess.Board(QUEEN_UP), [m("e1e2"), m("e8d7"), m("c3d5")])
        found = explain.merge(game, game.game, sub, sub.game.variations, "Hinweis")
        first = found[sub.first()]
        self.assertEqual(first.starting_comment, "Hinweis")
        self.assertEqual(first.variations[0].starting_comment, "")
        self.assertEqual(first.variations[0].variations[0].starting_comment, "")


@unittest.skipUnless(shutil.which("stockfish"), "stockfish nicht installiert")
class ExplainJobTest(unittest.TestCase):
    def test_job_explains_given_move(self):
        board = chess.Board("4k3/8/8/3q4/8/2N5/8/4K3 w - - 0 1")
        engine = chess.engine.SimpleEngine.popen_uci("stockfish")
        try:
            demo = explain.explain_job(board, m("c3d5"), chess.engine.Limit(depth=10))(engine)
        finally:
            engine.quit()
        self.assertEqual(demo.first().move, m("c3d5"))
        self.assertEqual(demo.game.board().fen(), board.fen())

    def test_why_not_shows_played_and_best_move(self):
        board = chess.Board("4k3/8/8/3q4/8/2N5/8/4K3 w - - 0 1")
        engine = chess.engine.SimpleEngine.popen_uci("stockfish")
        try:
            tree = explain.why_not_job(board, m("e1e2"), limit=chess.engine.Limit(depth=10))(engine)
        finally:
            engine.quit()
        self.assertEqual([n.move for n in tree.game.variations], [m("e1e2"), m("c3d5")])
        self.assertEqual(tree.label(tree.first()), "Gespielt")
        self.assertIn("Besser war Sxd5: Damit gewinnst du die Dame.", tree.first().comment)

    def test_why_not_for_the_game_tree_puts_the_reason_on_the_best_move(self):
        board = chess.Board("4k3/8/8/3q4/8/2N5/8/4K3 w - - 0 1")
        engine = chess.engine.SimpleEngine.popen_uci("stockfish")
        try:
            tree = explain.why_not_job(board, m("e1e2"), limit=chess.engine.Limit(depth=10),
                                       variation=True)(engine)
        finally:
            engine.quit()
        best = tree.game.variations[1]
        self.assertTrue(best.comment.startswith("Besser als Ke2. Damit gewinnst du die Dame."), best.comment)
        self.assertNotIn("Ausgangsstellung", best.comment)  # kein Wegweiser zur Vorführung

    def test_why_not_says_when_the_played_move_is_still_fine(self):
        # 10. Sf4 (statt 10. d4): Weiß steht danach weiter besser, d4 bringt nur mehr
        board = chess.Board()
        for san in "e4 d5 exd5 Qxd5 Nc3 Qa5 Bc4 c6 d3 Nf6 Ne2 Bg4 O-O e5 h3 Bh5 Qe1 Bc5".split():
            board.push_san(san)
        engine = chess.engine.SimpleEngine.popen_uci("stockfish")
        try:
            tree = explain.why_not_job(board, m("e2f4"), limit=chess.engine.Limit(depth=14),
                                       variation=True)(engine)
        finally:
            engine.quit()
        best = tree.game.variations[1]
        self.assertTrue(best.comment.startswith("Besser als Sf4. Sf4 ist in Ordnung, du stehst damit "
                                                "weiter besser. d4 holt aber mehr heraus"), best.comment)

    def test_hint_that_is_not_stockfishs_best_says_so(self):
        board = chess.Board("4k3/8/8/3q4/8/2N5/8/4K3 w - - 0 1")
        engine = chess.engine.SimpleEngine.popen_uci("stockfish")
        try:
            tree = explain.explain_job(board, m("e1e2"), limit=chess.engine.Limit(depth=10))(engine)
        finally:
            engine.quit()
        self.assertIn("Stockfish findet Sxd5 besser.", tree.first().comment)
        # beim Hovern über „Sxd5“ zeigt der Pfeil vom Springer auf c3, auch wenn er schon gezogen hat
        self.assertIn((chess.D5, chess.KNIGHT, chess.C3, chess.Piece(chess.KNIGHT, chess.WHITE)),
                      tree.refs(tree.first()))


class TradeTextTest(unittest.TestCase):
    def test_piece_for_pawn_is_named_not_netted(self):
        before = chess.Board("4k3/8/8/6p1/8/5N2/8/4K3 w - - 0 1")
        after = chess.Board("4k3/8/8/8/8/8/8/4K3 w - - 0 1")  # Sxg5 … und der Springer ist weg
        self.assertEqual(explain.trade_text(before, after, chess.WHITE),
                         "Du gibst einen Springer und bekommst einen Bauern")

    def test_plain_gain_and_exchange(self):
        before = chess.Board("3qk3/8/8/8/8/8/8/3QK1N1 w - - 0 1")
        self.assertEqual(explain.trade_text(before, chess.Board("4k3/8/8/8/8/8/8/3QK1N1 w - - 0 1"),
                                            chess.WHITE), "Du gewinnst die Dame")
        self.assertEqual(explain.trade_text(before, chess.Board("4k3/8/8/8/8/8/8/4K1N1 w - - 0 1"),
                                            chess.WHITE), "ein Abtausch, das Material bleibt gleich")

    def test_pieces_text_lists_most_valuable_first(self):
        self.assertEqual(explain.pieces_text({chess.PAWN: 2, chess.ROOK: 1}), "einen Turm und zwei Bauern")


class PawnAttackTest(unittest.TestCase):
    def test_piece_dodging_a_pawn_push_is_explained(self):
        board = chess.Board("rnbqkbnr/p3p3/1ppp1p2/6pp/2B1P3/2PP1N1P/PP3PP1/RNBQ1RK1 w kq - 0 8")
        text, shapes = explain.describe(board, m("f3h2"), chess.WHITE)
        self.assertEqual(text, ["Der Springer geht dem Angriff g4 aus dem Weg."])
        self.assertIn((chess.G5, chess.G4, "threat"), shapes)

    def test_no_dodge_when_the_pawn_would_just_be_taken(self):
        board = chess.Board("4k3/8/8/6p1/8/5N2/8/4K1R1 w - - 0 1")  # den Bauern auf g4 nähme der Turm
        self.assertIsNone(explain._pawn_attack(board, chess.F3))


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


class SuggestionTest(unittest.TestCase):
    """Nachspielen: nur der eigene Zug kommt in den Baum, Antworten bleiben anklickbare Vorschläge."""

    def sub_tree(self):
        board = chess.Board()
        game = chess.pgn.Game()
        e4 = game.add_variation(chess.Move.from_uci("e2e4"), comment="Du ziehst e4.")
        e5 = e4.add_variation(chess.Move.from_uci("e7e5"))
        c5 = e4.add_variation(chess.Move.from_uci("c7c5"))
        e5.add_variation(chess.Move.from_uci("g1f3"))
        sub = explain.Tree(game, start=board, hero=chess.WHITE)
        sub.info(e5).update(maia=0.6)
        sub.info(c5).update(maia=0.1)
        return sub

    def test_only_own_move_is_grafted(self):
        game = chess.pgn.Game()
        tree = explain.Tree(game, start=chess.Board(), hero=chess.WHITE)
        child = explain.graft_move(tree, game, self.sub_tree())
        self.assertEqual(child.move, chess.Move.from_uci("e2e4"))
        self.assertEqual(child.comment, "Du ziehst e4.")
        self.assertEqual(child.variations, [])
        self.assertEqual(explain.suggestions(tree, child),
                         [(chess.Move.from_uci("e7e5"), "Maia meistens"), (chess.Move.from_uci("c7c5"), "Maia selten")])

    def test_taking_a_suggestion_offers_the_next(self):
        game = chess.pgn.Game()
        tree = explain.Tree(game, start=chess.Board(), hero=chess.WHITE)
        child = explain.graft_move(tree, game, self.sub_tree())
        reply = explain.take_suggestion(tree, child, chess.Move.from_uci("e7e5"))
        self.assertEqual([c.move for c in child.variations], [chess.Move.from_uci("e7e5")])
        self.assertEqual(explain.suggestions(tree, child), [(chess.Move.from_uci("c7c5"), "Maia selten")])
        self.assertEqual([m for m, _ in explain.suggestions(tree, reply)], [chess.Move.from_uci("g1f3")])
