import os
import unittest

import chess

from schach import opening


def play(*sans):
    board = chess.Board()
    for san in sans:
        board.push_san(san)
    return board


class CourseTest(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.courses = {c.title: c for c in opening.load_courses()}
        cls.book = opening.Book()
        cls.names = opening.Names()

    def test_courses_load(self):
        self.assertIn("Italienisch", self.courses)
        self.assertIn("Spanisch", self.courses)
        self.assertEqual(self.courses["Italienisch"].color, chess.WHITE)
        for title in ("Zweispringerspiel", "Spanisch mit Schwarz", "Skandinavisch"):
            self.assertEqual(self.courses[title].color, chess.BLACK)
        for course in self.courses.values():
            self.assertTrue(course.welcome)
            self.assertGreaterEqual(opening.main_line_length(course), 10)

    def test_every_course_position_is_reachable_and_legal(self):
        for course in self.courses.values():
            self.assertIn(opening.key(course.start()), course.positions)

    def test_arrows_parsed_and_hidden_from_text(self):
        course = opening.parse_course(
            '[Event "T"]\n\n{ Start [%csl Re4] } 1. e4 { Zentrum! [%cal Gd1h5,Gf1c4] } *')
        option = course.options(chess.Board())[0]
        self.assertEqual(option.comment, "Zentrum!")
        self.assertEqual(option.shapes, ((chess.D1, chess.H5, "green"), (chess.F1, chess.C4, "green")))
        self.assertEqual(course.welcome, "Start")
        self.assertEqual(course.welcome_shapes, ((chess.E4, chess.E4, "red"),))

    def test_warum_variation_is_demo_not_option(self):
        course = opening.parse_course(
            '[Event "T"]\n\n1. e4 e5 2. Nf3 { Angriff auf e5. } '
            '( 2. Qh5 { [%warum] Stell dir vor … } 2... Nc6 { Gedeckt. [%cal Gc6e5] } ) 2... Nc6 *')
        before = play("e4", "e5")
        self.assertEqual([o.move.uci() for o in course.options(before)], ["g1f3"])
        [demo] = course.demos_for(before, chess.Move.from_uci("g1f3"))
        self.assertEqual([m.uci() for m, _c, _s in demo.steps], ["d1h5", "b8c6"])
        self.assertEqual(demo.steps[0][1], "Stell dir vor …")
        self.assertEqual(demo.steps[1][2], ((chess.C6, chess.E5, "green"),))
        self.assertEqual(demo.board_at(1).fen().split()[0], "r1bqkbnr/pppp1ppp/2n5/4p2Q/4P3/8/PPPP1PPP/RNB1KBNR")
        self.assertEqual(course.demos_for(before, chess.Move.from_uci("d1h5")), [])
        self.assertEqual(demo.title, "")
        titled = opening.parse_course('[Event "T"]\n\n1. e4 ( 1. e4 { [%warum Wozu e4?] x } ) *')
        self.assertEqual(titled.demos_for(chess.Board(), chess.Move.from_uci("e2e4"))[0].title, "Wozu e4?")

    def test_several_demos_per_move_and_demo_for_alternative(self):
        course = opening.parse_course(
            '[Event "T"]\n\n1. e4 e5 2. Nf3 ( 2. Nf3 { [%warum Wozu Sf3?] a } 2... Nc6 ) '
            '( 2. Qh5 { [%warum Und Dh5?] b } 2... Nc6 ) ( 2. Bc4 { auch gut } ) '
            '( 2. Bc4 { [%warum Warum Lc4?] c } 2... Nf6 ) 2... Nc6 *')
        before = play("e4", "e5")
        main = course.demos_for(before, chess.Move.from_uci("g1f3"))
        self.assertEqual([d.title for d in main], ["Wozu Sf3?", "Und Dh5?"])  # Was-wäre-wenn hängt am Hauptzug
        alt = course.demos_for(before, chess.Move.from_uci("f1c4"))
        self.assertEqual([d.title for d in alt], ["Warum Lc4?"])  # erklärt die Alternative selbst
        self.assertEqual({o.move.uci() for o in course.options(before)}, {"g1f3", "f1c4"})

    def test_options_main_first(self):
        italian = self.courses["Italienisch"]
        options = italian.options(play("e4", "e5", "Nf3", "Nc6", "Bc4"))
        self.assertEqual(options[0].move, chess.Move.from_uci("f8c5"))
        self.assertTrue(options[0].main)
        self.assertEqual({o.move.uci() for o in options}, {"f8c5", "g8f6", "f8e7"})

    def test_transposition_continues_main_line(self):
        italian = self.courses["Italienisch"]
        # 3...Sf6 4.d3 Lc5 5.c3 ist dieselbe Stellung wie 3...Lc5 4.c3 Sf6 5.d3
        via_side = play("e4", "e5", "Nf3", "Nc6", "Bc4", "Nf6", "d3", "Bc5", "c3")
        via_main = play("e4", "e5", "Nf3", "Nc6", "Bc4", "Bc5", "c3", "Nf6", "d3")
        self.assertEqual(opening.key(via_side), opening.key(via_main))
        self.assertTrue(italian.options(via_side))

    def test_judge(self):
        italian = self.courses["Italienisch"]
        before = play("e4", "e5", "Nf3", "Nc6")
        verdict = opening.judge(italian, self.book, self.names, before, chess.Move.from_uci("f1c4"))
        self.assertEqual(verdict.kind, "course")
        self.assertIn("f7", verdict.option.comment)
        spanish = opening.judge(italian, self.book, self.names, before, chess.Move.from_uci("f1b5"))
        self.assertEqual(spanish.kind, "book")
        weird = opening.judge(italian, self.book, self.names, before, chess.Move.from_uci("h2h4"))
        self.assertEqual(weird.kind, "other")

    def test_judge_transposition(self):
        italian = self.courses["Italienisch"]
        # Andere Zugfolge in eine Kursstellung: 4.d3 vor c3 in der Hauptvariante
        before = play("e4", "e5", "Nf3", "Nc6", "Bc4", "Bc5")
        verdict = opening.judge(italian, self.book, self.names, before, chess.Move.from_uci("d2d3"))
        self.assertIn(verdict.kind, ("transposition", "book", "other"))
        before = play("e4", "e5", "Nf3", "Nc6", "Bc4", "Nf6", "d3", "Bc5")
        self.assertEqual(
            opening.judge(italian, self.book, self.names, before, chess.Move.from_uci("c2c3")).kind, "course"
        )


class NamesTest(unittest.TestCase):
    def test_english_names_translated_whole(self):
        self.assertEqual(opening._german("King's Pawn"), "Königsbauernspiel")
        self.assertEqual(opening._german("Queen's Pawn Game"), "Damenbauernspiel")
        self.assertEqual(opening._german("Dutch Defense: Leningrad Variation"), "Holländisch: Leningrad-Variante")
        self.assertEqual(opening._german("Caro-Kann Defense: Advance Variation"), "Caro-Kann: Vorstoßvariante")
        self.assertEqual(opening._german("Rat Defense: Small Center"), "Rat Defense: Small Center")  # lieber ganz englisch

    def test_names(self):
        names = opening.Names()
        self.assertTrue(names.name(play("e4", "e5", "Nf3", "Nc6", "Bc4")).startswith("Italien"))
        self.assertTrue(names.name(play("e4", "e5", "Nf3", "Nc6", "Bb5")).startswith("Spanisch"))
        self.assertEqual(names.exact(play("c4")), "Englisch")  # nicht „Abarten von Holländisch“
        # unbekannte Stellung: Name der letzten bekannten
        self.assertTrue(names.name(play("e4", "e5", "Nf3", "Nc6", "Bc4", "h6", "a3", "a6")))


class BookTest(unittest.TestCase):
    def test_book_knows_main_moves(self):
        moves = [m.uci() for m, _w in opening.Book().moves(play("e4", "e5", "Nf3", "Nc6"))]
        self.assertEqual(moves[:2], ["f1b5", "f1c4"])


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


class BooksTest(unittest.TestCase):
    """Mehrere Polyglot-Bücher: Fundorte, Doppelte, Vereinigung."""

    @staticmethod
    def _write_book(path, entries):
        import struct
        data = b"".join(struct.pack(">QHHI", key, raw, weight, 0) for key, raw, weight in sorted(entries))
        with open(path, "wb") as fh:
            fh.write(data)

    @staticmethod
    def _raw(move):
        promo = {None: 0, chess.KNIGHT: 1, chess.BISHOP: 2, chess.ROOK: 3, chess.QUEEN: 4}[move.promotion]
        return (chess.square_file(move.to_square) | chess.square_rank(move.to_square) << 3
                | chess.square_file(move.from_square) << 6 | chess.square_rank(move.from_square) << 9 | promo << 12)

    def setUp(self):
        import tempfile
        self.dir = tempfile.TemporaryDirectory()
        self.addCleanup(self.dir.cleanup)
        start = chess.polyglot.zobrist_hash(chess.Board())
        e4, d4, c4 = (chess.Move.from_uci(u) for u in ("e2e4", "d2d4", "c2c4"))
        self.a = os.path.join(self.dir.name, "a.bin")
        self.b = os.path.join(self.dir.name, "b_buch.bin")
        self._write_book(self.a, [(start, self._raw(e4), 3), (start, self._raw(d4), 1)])
        self._write_book(self.b, [(start, self._raw(c4), 10)])
        self.e4, self.d4, self.c4 = e4, d4, c4

    def test_paths_without_duplicates(self):
        link = os.path.join(self.dir.name, "link.bin")
        os.symlink(self.a, link)
        paths = opening.book_paths(extra=[link, "/gibt/es/nicht.bin"], book_dir=self.dir.name, builtin=None)
        self.assertEqual(paths, [link, self.b])  # a.bin ist dieselbe Datei wie link.bin

    def test_copy_of_builtin_counts_once(self):
        import shutil
        copy = os.path.join(self.dir.name, "kopie.bin")
        shutil.copy(opening.BOOK_PATH, copy)
        paths = opening.book_paths(book_dir=self.dir.name)
        self.assertEqual(paths[0], opening.BOOK_PATH)
        self.assertNotIn(copy, paths)

    def test_bundled_data_present(self):
        self.assertTrue(opening.Book().available)
        board = chess.Board()
        for san in ("e4", "e5", "Nf3", "Nc6", "Bc4"):
            board.push_san(san)
        self.assertIn("Italien", opening.Names().name(board) or "")

    def test_union(self):
        books = opening.Books([self.a, self.b])
        self.assertEqual([b.name for b in books.books], ["a", "b buch"])
        board = chess.Board()
        self.assertTrue(books.contains(board, self.c4))
        self.assertTrue(books.contains(board, self.e4))
        shares = dict(books.moves(board))
        self.assertAlmostEqual(shares[self.c4], 0.5)  # je Buch normiert, dann gemittelt
        self.assertAlmostEqual(shares[self.e4], 0.375)
        self.assertAlmostEqual(sum(shares.values()), 1)

    def test_missing_and_empty(self):
        books = opening.Books([os.path.join(self.dir.name, "fehlt.bin")])
        self.assertEqual(books.books, [])
        self.assertEqual(books.moves(chess.Board()), [])
        self.assertFalse(books.contains(chess.Board(), self.e4))


class SquareNamesTest(unittest.TestCase):
    def test_squares_in_comment(self):
        from schach.training import squares_in
        text = "Lc4 zielt auf f7. Sxe5, Sbd2, exd5 und e4 – aber nicht Ende4 oder a10. Die f7-Schwäche!"
        found = [(text[a:b], chess.square_name(sq), piece, extra) for a, b, sq, piece, extra in squares_in(text)]
        self.assertEqual(found, [("Lc4", "c4", "L", ""), ("f7", "f7", None, ""), ("Sxe5", "e5", "S", ""),
                                 ("Sbd2", "d2", "S", "b"), ("exd5", "d5", "P", "e"), ("e4", "e4", None, ""),
                                 ("f7", "f7", None, "")])

    def test_mover_finds_the_piece(self):
        from schach.training import mover
        board = chess.Board()
        for san in ("e4", "e5", "Nf3", "Nc6"):
            board.push_san(san)
        self.assertEqual(mover(board, "L", "", chess.C4), chess.F1)  # Lc4 kommt noch: Pfeil von f1
        self.assertEqual(mover(board, "S", "", chess.F6), chess.G8)  # auch für die andere Seite
        self.assertIsNone(mover(board, "S", "", chess.F3))  # steht schon dort
        self.assertIsNone(mover(board, None, "", chess.E4))  # nur ein Feld
        start = chess.Board()
        self.assertEqual(mover(start, "L", "", chess.F4), chess.C1)  # Aufbau-Plan: der schwarzfeldrige Läufer
        self.assertEqual(mover(start, "S", "", chess.D2), chess.B1)  # nur einer passt
        self.assertIsNone(mover(start, "T", "", chess.D1))  # zwei Türme könnten: lieber kein Pfeil

    def test_mover_finds_capturing_pawn(self):
        from schach.training import mover, route
        # nach 7. Lb3: c4 ist leer, die Drohung bxc4 zeigt trotzdem vom Bauern b5 aus
        board = chess.Board("rn1qkb1r/5ppp/2pp1n2/1p2p3/4P1b1/1B1P1N2/PPP2PPP/RNBQR1K1 b kq - 1 7")
        self.assertEqual(mover(board, "P", "b", chess.C4), chess.B5)
        self.assertEqual(route(board, "Das wehrt die Drohung bxc4 ab.", "P", "b", chess.C4), (chess.B5, None))
        self.assertIsNone(mover(board, "P", "e", chess.C4))  # auf der e-Linie greift kein Bauer c4 an

    def test_route_bridges_over_earlier_move(self):
        from schach.training import route
        start = chess.Board()
        text = "Aufbau d4–Lf4–e3–Sf3–c3–Ld3–Sbd2, dann e4 oder Se5."
        self.assertEqual(route(start, text, "S", "", chess.E5), (chess.G1, chess.F3))  # g1→f3→e5
        self.assertEqual(route(start, text, "L", "", chess.F4), (chess.C1, None))  # geht direkt
        self.assertEqual(route(start, "Plan: Se5", "S", "", chess.E5), (None, None))  # keine Brücke im Text

    def test_mark_squares_leaves_tags_alone(self):
        from schach.training import mark_squares
        out = mark_squares("<span alpha='70%'>Warum?</span>\n<b>3. Lc4</b> – auf f7")
        self.assertIn("<span alpha='70%'>Warum?</span>", out)
        self.assertEqual(out.count("<i>"), 2)
        self.assertIn("<i>Lc4</i></b>", out)
