import shutil
import unittest

import chess
import chess.engine

from schach import annotate, explain
from chess.engine import Cp, Mate

# Partie gegen Maia 600: Weiß hat früh die Dame gewonnen und tut sich beim Mattsetzen schwer
GAME = ("e4 e5 Nf3 d6 Bc4 Nf6 d3 Bg4 O-O c6 Re1 b5 Bb3 Qa5 Bd2 d5 Bxa5 Bxf3 gxf3 Nh5 exd5 Nd7 "
        "dxc6 Be7 cxd7+ Kxd7 d4 Bh4 dxe5+ Ke7 e6 f5 Qd7+ Kf6 e7 Nf4 Qe6+ Kg5 Qf7 a6 Qxg7+ Kh5 "
        "Bf7+ Ng6 Re6 h6 Rxg6 Bg5 Rxg5+ Kh4").split()


def at(plies):
    board = chess.Board()
    for san in GAME[:plies]:
        board.push_san(san)
    return board


def lines(board, **moves):
    """{Zug: (Bewertung, Hauptlinie)} aus SAN-Ketten: lines(b, Qd7=(Cp(2000), "Qd7+ Kf6"))."""
    result = {}
    for score, sans in moves.values():
        probe, pv = board.copy(), []
        for san in sans.split():
            pv.append(probe.push_san(san))
        result[pv[0]] = (score, pv)
    return result


class MateTest(unittest.TestCase):
    def setUp(self):
        self.board = at(30)  # 16. ?, Weiß am Zug

    def classify(self, best, played, depth=18):
        found = lines(self.board, a=(best, "Qd5"), b=(played, "e6"))
        return annotate.classify(self.board, self.board.parse_san("e6"), found, depth)

    def test_lost_mate_like_lichess(self):
        self.assertEqual(self.classify(Mate(5), Cp(1766)), "?!")  # danach noch über +10
        self.assertEqual(self.classify(Mate(5), Cp(800)), "?")
        self.assertEqual(self.classify(Mate(5), Cp(300)), "??")
        self.assertEqual(self.classify(Mate(5), Mate(-3)), "??")

    def test_lost_mate_only_as_long_as_the_depth_sees_it_reliably(self):
        self.assertEqual(annotate.mate_horizon(14), 4)  # Mindesttiefe, schnell gezogen oder Nachbewertung
        self.assertEqual(annotate.mate_horizon(18), 5)  # Energiesparen
        self.assertEqual(annotate.mate_horizon(30), 5)  # Normal: mehr braucht es nicht
        self.assertIsNone(self.classify(Mate(5), Cp(1766), depth=14))
        self.assertEqual(self.classify(Mate(4), Cp(1766), depth=14), "?!")
        self.assertIsNone(self.classify(Mate(9), Cp(1766), depth=30))

    def test_short_mate_missed(self):
        self.assertEqual(self.classify(Mate(1), Mate(3)), "?!")
        self.assertEqual(self.classify(Mate(2), Mate(4)), "?!")

    def test_longer_mate_only_delayed_is_fine(self):
        self.assertIsNone(self.classify(Mate(3), Mate(5)))  # wie Lichess „MateDelayed“
        self.assertIsNone(self.classify(Mate(2), Mate(2)))


class NeedlessLossTest(unittest.TestCase):
    def test_queen_given_away_while_another_move_keeps_it(self):
        board = at(32)  # 17. Dd7+ wurde gespielt, Dd8+ zurückgenommen
        found = lines(board, a=(Cp(2020), "Qd7+ Kf6 Qf7+ Kg5"), b=(Cp(2063), "Qd8+ Raxd8 Nc3"))
        self.assertEqual(annotate.classify(board, board.parse_san("Qd8+"), found), "?!")
        self.assertIsNone(annotate.classify(board, board.parse_san("Qd7+"), found))

    def test_no_sign_if_the_material_keeping_move_is_clearly_worse(self):
        board = at(32)
        found = lines(board, a=(Cp(200), "Qd7+ Kf6 Qf7+ Kg5"), b=(Cp(2063), "Qd8+ Raxd8 Nc3"))
        self.assertEqual(annotate.classify(board, board.parse_san("Qd8+"), found), "!!")  # einziger Zug, ein Opfer

    def test_sacrifice_for_faster_mate_is_fine(self):
        board = at(50)  # 26. ?, Weiß am Zug
        found = lines(board, a=(Mate(3), "Qxh8 Rxh8"), b=(Mate(5), "Rg2 b4"))
        self.assertIsNone(annotate.classify(board, board.parse_san("Qxh8"), found))

    def test_material_change_waits_for_the_recapture(self):
        board = at(32)
        pv = lines(board, a=(Cp(0), "Qd8+ Raxd8 Nc3"))
        self.assertEqual(annotate.material_change(board, next(iter(pv.values()))[1]), -9)


@unittest.skipUnless(shutil.which("stockfish"), "stockfish nicht installiert")
class WhyNotTest(unittest.TestCase):
    def why_not(self, board, san):
        engine = chess.engine.SimpleEngine.popen_uci("stockfish")
        try:
            return explain.why_not_job(board, board.parse_san(san), limit=chess.engine.Limit(depth=14))(engine)
        finally:
            engine.quit()

    def test_missed_mate_in_one(self):
        tree = self.why_not(at(46), "Rxg6")
        self.assertIn("Besser war Dxg6#: Damit setzt du sofort matt.", tree.first().comment)

    def test_queen_given_away(self):
        tree = self.why_not(at(32), "Qd8+")
        self.assertIn("Damit behältst du die Dame.", tree.first().comment)


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