import unittest

import chess

from schach import explorer, opening


class LichessLinesTest(unittest.TestCase):
    def test_parse_and_castling(self):
        board = chess.Board("r3k2r/8/8/8/8/8/8/R3K2R w KQkq - 0 1")
        data = {"moves": [
            {"uci": "e1h1", "san": "O-O", "white": 6, "draws": 2, "black": 2},
            {"uci": "a1a8", "san": "Rxa8+", "white": 1, "draws": 0, "black": 1},
            {"uci": "zz", "white": 1},
        ]}
        lines = explorer.lichess_lines(data, board)
        self.assertEqual([l.move.uci() for l in lines], ["e1g1", "a1a8"])
        self.assertEqual(lines[0].games, 10)
        self.assertAlmostEqual(lines[0].share, 10 / 13)  # Anteil an allen Partien der Stellung

    def test_illegal_moves_skipped(self):
        data = {"moves": [{"uci": "e2e5", "white": 1, "draws": 0, "black": 0}]}
        self.assertEqual(explorer.lichess_lines(data, chess.Board()), [])


class BookLinesTest(unittest.TestCase):
    def test_book_share(self):
        class FakeBook:
            def moves(self, board):
                return [(chess.Move.from_uci("e2e4"), 3), (chess.Move.from_uci("d2d4"), 1)]
        lines = explorer.book_lines(FakeBook(), chess.Board())
        self.assertEqual([round(l.share, 2) for l in lines], [0.75, 0.25])

    def test_real_book_if_present(self):
        lines = explorer.book_lines(opening.Book(), chess.Board())
        if lines:
            self.assertAlmostEqual(sum(l.share for l in explorer.book_lines(opening.Book(), chess.Board())), 1, 1)


class HelpersTest(unittest.TestCase):
    def test_ratings_near(self):
        self.assertEqual(explorer.ratings_near(1250), [1200, 1400])
        self.assertEqual(explorer.ratings_near(700), [0, 1000])
        self.assertEqual(explorer.ratings_near(2700), [2200, 2500])

    def test_games_text(self):
        self.assertEqual(explorer.games_text(1234), "1.234")
        self.assertEqual(explorer.games_text(45678), "45 Tsd.")
        self.assertEqual(explorer.games_text(2_345_678), "2,3 Mio.")


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