import io
from html import escape as html_escape, unescape
import re
import shutil
import subprocess
import tempfile
import unittest

import chess
import chess.pgn

from schach import export, notation, savegames

MOVES = "e4 e5 Nf3 Nc6 Bc4 Nd4 Nxe5 Qg5 Nxf7 Qxg2 Rf1 Qxe4+ Be2 Nf3#".split()


def sample():
    board = chess.Board()
    for san in MOVES:
        board.push_san(san)
    return savegames.GameState(
        board=board, human=chess.WHITE, elo=1500, symbols={5: "!", 6: "??", 13: "!!"},
        evals={i: 50.0 + i for i in range(len(MOVES))}, names=("Florian", "Max"), mode="review",
        name="Vereinsabend",
    )


def opts(**kw):
    kw.setdefault("theme", "cburnett")
    return export.Options(**kw)


class TextFormatsTest(unittest.TestCase):
    def test_fen_of_shown_position(self):
        fen = export.export("fen", sample(), opts(plies=2))
        self.assertEqual(fen.strip(), "rnbqkbnr/pppp1ppp/8/4p3/4P3/8/PPPP1PPP/RNBQKBNR w KQkq - 0 2")

    def test_fen_ignores_game_scope(self):
        self.assertEqual(export.export("fen", sample(), opts(scope="game", plies=0)).strip(), chess.STARTING_FEN)

    def test_pgn_game_keeps_or_drops_annotations(self):
        full = export.export("pgn", sample(), opts(scope="game"))
        self.assertIn("$4", full)
        self.assertIn("[%wp", full)
        bare = export.export("pgn", sample(), opts(scope="game", symbols=False, evals=False))
        self.assertNotIn("$", bare.split("\n\n", 1)[1])
        self.assertNotIn("[%wp", bare)
        game = chess.pgn.read_game(io.StringIO(bare))
        self.assertEqual(len(list(game.mainline_moves())), len(MOVES))

    def test_pgn_position_is_setup_without_moves(self):
        text = export.export("pgn", sample(), opts(plies=4))
        game = chess.pgn.read_game(io.StringIO(text))
        self.assertEqual(game.headers["White"], "Florian")
        self.assertEqual(list(game.mainline_moves()), [])
        self.assertEqual(game.board().fen(), export.board_at(sample(), 4).fen())
        self.assertNotIn("SchachHuman", text)

    def test_ascii_board_and_moves(self):
        text = export.export("ascii", sample(), opts(scope="game", plies=0, notation="de"))
        self.assertIn("8 | t s l d k l s t |", text)
        self.assertIn("1 | T S L D K L S T |", text)
        self.assertIn("2. Sf3 Sc6 3. Lc4 Sd4!", text)
        self.assertIn("Florian – Max", text)
        self.assertIn("0–1", text)
        self.assertTrue(text.isascii() is False)  # Gedankenstrich im Kopf

    def test_ascii_flipped_and_english(self):
        text = export.export("ascii", sample(), opts(plies=0, flipped=True, notation="en", players=False))
        lines = text.splitlines()
        self.assertEqual(lines[1], "1 | R N B K Q B N R |")
        self.assertEqual(lines[-4].strip(), "h g f e d c b a")
        self.assertNotIn("Florian", text)

    def test_caption(self):
        board = export.board_at(sample(), 8)
        self.assertEqual(export.caption(board, "de"), "Stellung nach 4… Dg5 · Weiß am Zug")
        self.assertTrue(export.caption(sample().board).endswith("Weiß ist matt"))
        self.assertTrue(export.caption(chess.Board()).startswith("Ausgangsstellung"))


class VariationTest(unittest.TestCase):
    """Nebenvarianten vom Analysebrett: in PGN und HTML, abschaltbar."""

    def state(self):
        state = sample()
        m = chess.Move.from_uci
        # nach 3. Lc4 (Halbzug 4): 3… Sf6 statt 3… Sd4, mit Kommentar, Pfeil und Fortsetzung
        state.variations = {4: [(m("g8f6"), "So spielt Maia 600 oft.", ((chess.G8, chess.F6, "threat"),),
                                 [(m("f3g5"), "Du greifst f7 an.", (), [])])]}
        return state

    def test_pgn_contains_variation_with_comment_and_arrow(self):
        text = savegames.to_pgn(self.state())
        self.assertIn("( 3... Nf6 { [%cal Yg8f6] So spielt Maia 600 oft. } 4. Ng5 { Du greifst f7 an. } )", text)
        game = chess.pgn.read_game(io.StringIO(text))
        self.assertEqual([n.san() for n in game.mainline()], MOVES)  # Hauptlinie bleibt die Partie

    def test_export_can_drop_variations(self):
        with_them = export.export("pgn", self.state(), opts(scope="game"))
        without = export.export("pgn", self.state(), opts(scope="game", variations=False))
        self.assertIn("3... Nf6", with_them)
        self.assertNotIn("3... Nf6", without)

    def test_saved_variations_come_back(self):
        state = self.state()
        loaded = savegames.from_pgn(savegames.to_pgn(state))
        # Kommentar ohne [%cal]; die Drohung kommt als Lichess-Gelb zurück (gelb bleibt gelb beim Zeichnen)
        (move, comment, shapes, children, name), = loaded.variations[4]
        self.assertEqual((move, comment), state.variations[4][0][:2])
        self.assertEqual([c[:4] for c in children], state.variations[4][0][3])
        self.assertEqual(shapes, ((chess.G8, chess.F6, "yellow"),))
        self.assertEqual(name, "")

    def test_variation_name_survives_saving(self):
        state = self.state()
        move, comment, shapes, children = state.variations[4][0]
        state.variations = {4: [(move, comment, shapes, children, "Zweispringerspiel")]}
        text = savegames.to_pgn(state)
        self.assertIn("( { Zweispringerspiel } 3... Nf6", text)
        self.assertEqual(savegames.from_pgn(text).variations[4][0][4], "Zweispringerspiel")

    def test_drawn_shapes_on_the_game_come_back_in_lichess_colors(self):
        state = sample()
        state.shapes = {-1: ((chess.E2, chess.E4, "green"),),
                        2: ((chess.F7, chess.F7, "red"), (chess.B1, chess.C3, "blue"), (chess.D8, chess.H4, "yellow"))}
        text = savegames.to_pgn(state)
        self.assertIn("[%csl Rf7]", text)
        self.assertIn("[%cal Bb1c3,Yd8h4]", text)
        loaded = savegames.from_pgn(text)
        self.assertEqual(loaded.shapes, state.shapes)
        self.assertEqual(state.truncated(1).shapes, {-1: state.shapes[-1]})

    def test_branching_off_keeps_earlier_variations_only(self):
        state = self.state()
        self.assertEqual(state.truncated(3).variations, {})  # Variante hängt nach Halbzug 4, also dahinter
        self.assertEqual(state.truncated(4).variations, state.variations)  # hängt noch am letzten Zug

    def test_html_shows_variation_without_commands(self):
        page = export.export("html", self.state(), opts(scope="game"))
        self.assertIn("( 3... Nf6 { So spielt Maia 600 oft. } 4. Ng5", unescape(page))


class LatexTest(unittest.TestCase):
    def test_game_splits_mainline_at_diagram(self):
        tex = export.export("latex", sample(), opts(scope="game", plies=8, flipped=True))
        self.assertIn("\\mainline{1. e4 e5 2. Nf3 Nc6 3. Bc4 Nd4! 4. Nxe5?? Qg5}", tex)
        self.assertIn("\\mainline{5. Nxf7", tex)
        self.assertIn("inverse", tex)
        self.assertIn("markfields={d8,g5}", tex)
        self.assertLess(tex.index("\\chessboard"), tex.index("\\mainline{5."))

    def test_position_sets_fen_and_escapes_names(self):
        state = sample()
        state.names = ("A & B", "50%")
        tex = export.export("latex", state, opts(plies=4, last_move=False))
        self.assertIn("setfen=" + export.board_at(state, 4).fen(), tex)
        self.assertIn("A \\& B -- 50\\%", tex)
        self.assertNotIn("markfields", tex)

    @unittest.skipUnless(export.latex_available(), "pdflatex fehlt")
    def test_pdf_via_latex(self):
        pdf = export.export("pdf-latex", sample(), opts(scope="game", plies=8))
        self.assertTrue(pdf.startswith(b"%PDF"))


class ImageAndPageTest(unittest.TestCase):
    def test_svg_and_png(self):
        svg = export.export("svg", sample(), opts(scope="game", plies=8))
        self.assertIn("<svg", svg)
        png = export.export("png", sample(), opts(plies=8, players=False, evals=False))
        self.assertTrue(png.startswith(b"\x89PNG"))
        width, height = int.from_bytes(png[16:20], "big"), int.from_bytes(png[20:24], "big")
        self.assertEqual((width, height), (800, 800))  # ohne Köpfe und Balken: quadratisch

    def test_pdf(self):
        for scope in ("position", "game"):
            pdf = export.export("pdf", sample(), opts(scope=scope, plies=8))
            self.assertTrue(pdf.startswith(b"%PDF"))

    @unittest.skipUnless(shutil.which("pdfinfo"), "pdfinfo fehlt")
    def test_long_game_pdf_gets_more_pages(self):
        state = sample()
        board = chess.Board()
        for _ in range(60):  # Springer hin und her: 120 Züge
            for san in ("Nf3", "Nf6", "Ng1", "Ng8"):
                board.push_san(san)
        state.board, state.symbols, state.evals = board, {}, {}
        pdf = export.export("pdf", state, opts(scope="game"))
        with tempfile.NamedTemporaryFile(suffix=".pdf") as fh:
            fh.write(pdf)
            fh.flush()
            info = subprocess.run(["pdfinfo", fh.name], capture_output=True, text=True).stdout
        self.assertEqual(int(re.search(r"Pages:\s+(\d+)", info).group(1)), 2)

    def test_html_game_has_one_group_per_position(self):
        page = export.export("html", sample(), opts(scope="game", plies=8))
        groups = re.findall(r'<g class="ply" data-ply="(\d+)"( style="display:none")?>', page)
        self.assertEqual(len(groups), len(MOVES) + 1)
        visible = [ply for ply, hidden in groups if not hidden]
        self.assertEqual(visible, ["8"])
        self.assertIn('"start": 8', page)
        self.assertIn("user-select: all", page)
        self.assertIn("Sxe5", page)
        # PGN mit Zügen als Spans, der gezeigte (8. Halbzug) ist markiert
        self.assertIn('<span class="mv sel" data-ply="8">Qg5</span>', page)
        self.assertEqual(len(re.findall(r'<span class="mv', page)), len(MOVES))
        # Zugzeichen farbig statt NAG-Nummer, auch im kopierbaren PGN
        self.assertRegex(page, r'data-ply="7">Nxe5<b class="s" style="color:#[0-9a-f]{6}">\?\?</b></span>')
        self.assertIn('"pgn": "[Event', page)
        self.assertIn("Nxe5??", page)
        self.assertNotIn("$4", page)
        self.assertNotIn("SchachHuman", page)
        # Gewinnchance nur als Balken, nicht im PGN der Seite
        self.assertNotIn("[%wp", page)
        # Nummer, Zug und Ergebnis bleiben zusammen
        self.assertIn('<span class="u">1. <span class="mv" data-ply="1">e4</span></span>', page)
        # (Die Testpartie ist die Falle des Blackburne-Shilling-Gambits: eco.db kennt sie bis zum Matt,
        # der lange Kommentar „Bis hier: …“ steht daher als eigener Teil vor dem Ergebnis.)
        self.assertRegex(page, r'data-ply="14">Nf3#<b[^>]*>!!</b></span></span> <span class="c">\{ Bis hier: C50 [^<]*\}</span> <span class="u">0-1</span>')

    def test_html_pgn_long_comment_may_wrap(self):
        game = chess.pgn.read_game(io.StringIO(export.export("pgn", sample(), opts(scope="game"))))
        game.end().comment = "sehr langer Kommentar " * 5
        html = export._html_pgn(str(game), None)
        self.assertRegex(html, r'</span> <span class="c">\{ sehr langer')  # nicht in der Einheit
        self.assertTrue(html.endswith('<span class="u">0-1</span>'))

    def test_html_position_only(self):
        page = export.export("html", sample(), opts(plies=3, players=False))
        self.assertEqual(len(re.findall(r'<g class="ply"', page)), 1)
        self.assertNotIn('class="moves"', page)
        self.assertNotIn("Florian", page)

    def test_html_escapes_script_end(self):
        state = sample()
        state.names = ("</script><b>", "Max")
        page = export.export("html", state, opts(scope="game"))
        self.assertEqual(page.count("</script>"), 2)


class OpeningTest(unittest.TestCase):
    def setUp(self):
        if export._names()._conn is None:
            self.skipTest("eco.db von PyChess fehlt")

    def test_game_pgn_names_opening_and_marks_book_end(self):
        text = export.export("pgn", sample(), opts(scope="game"))
        game = chess.pgn.read_game(io.StringIO(text))
        self.assertRegex(game.headers["ECO"], r"^[A-E]\d\d$")
        self.assertTrue(game.headers["Opening"])
        ply, eco, name = export.book_end(sample())
        self.assertIsNotNone(ply)
        node = list(game.mainline())[ply]
        self.assertTrue(node.comment.startswith(f"Bis hier: {eco} {name}"))
        self.assertIn("[%wp", node.comment)  # Bewertung bleibt in der Datei erhalten
        # Wieder einlesen: Balkenwert kommt trotz Eröffnungskommentar zurück
        self.assertEqual(savegames.from_pgn(text).evals[ply], sample().evals[ply])

    def test_position_at_start_has_no_opening(self):
        text = export.export("pgn", sample(), opts(plies=0))
        self.assertNotIn("[ECO", text)
        self.assertIn("[Opening", export.export("pgn", sample(), opts(plies=5)))

    def test_html_meta_shows_opening(self):
        page = export.export("html", sample(), opts(scope="game"))
        _, eco, name = export.book_end(sample())
        self.assertIn(html_escape(f"{eco} {name}"), page)
        self.assertIn("Bis hier:", page)


def png_chunks(data):
    """[(typ, inhalt)] einer PNG-Datei."""
    chunks, pos = [], 8
    while pos < len(data):
        length = int.from_bytes(data[pos:pos + 4], "big")
        chunks.append((data[pos + 4:pos + 8], data[pos + 8:pos + 8 + length]))
        pos += 12 + length
    return chunks


def frame_delays(data):
    """Dauer jedes Bilds in ms aus den fcTL-Blöcken."""
    return [round(int.from_bytes(body[20:22], "big") * 1000 / int.from_bytes(body[22:24], "big"))
            for kind, body in png_chunks(data) if kind == b"fcTL"]


class AnimationTest(unittest.TestCase):
    def test_apng_structure(self):
        data = export.export("apng", sample(), opts(scope="game"))
        self.assertTrue(data.startswith(b"\x89PNG\r\n\x1a\n"))
        chunks = png_chunks(data)
        kinds = [kind for kind, _ in chunks]
        self.assertEqual(kinds[:4], [b"IHDR", b"acTL", b"fcTL", b"IDAT"])  # erstes Bild auch ohne APNG sichtbar
        self.assertEqual(kinds[-1], b"IEND")
        frames = int.from_bytes(chunks[1][1][:4], "big")
        self.assertEqual(frames, len(MOVES) + 1)  # Ausgangsstellung + jeder Halbzug
        self.assertEqual(kinds.count(b"fcTL"), frames)
        # Folgenummern über fcTL und fdAT lückenlos ab 0
        numbers = [int.from_bytes(body[:4], "big") for kind, body in chunks if kind in (b"fcTL", b"fdAT")]
        self.assertEqual(numbers, list(range(len(numbers))))
        width = int.from_bytes(chunks[0][1][:4], "big")
        self.assertEqual(width, export.APNG_WIDTH)

    def test_frames_match_single_images(self):
        """Die Auflagen setzen sich genau zu den einzelnen Stellungen zusammen."""
        import cairo
        import io as io_mod
        try:
            from PIL import Image
        except ImportError:
            self.skipTest("Pillow fehlt")
        o = opts(scope="game", plies=6)
        state = sample()
        state.board = export.board_at(state, 6)
        animation = Image.open(io_mod.BytesIO(export.export("apng", state, o)))
        for index, (diagram, _delay) in enumerate(export._frames(state, o)):
            width = export.APNG_WIDTH
            surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, animation.size[1])
            cr = cairo.Context(surface)
            cr.set_source_rgb(*export.APNG_BACKGROUND)
            cr.paint()
            diagram.render(cr, 0, 0, width)
            out = io_mod.BytesIO()
            surface.write_to_png(out)
            animation.seek(index)
            self.assertEqual(animation.convert("RGBA").tobytes(),
                             Image.open(out).convert("RGBA").tobytes(), f"Bild {index}")

    def test_delays_fixed_or_from_move_times(self):
        state = sample()
        state.times = {ply: 500 * (ply + 1) for ply in range(len(MOVES))}
        fixed = frame_delays(export.export("apng", state, opts(scope="game")))
        self.assertEqual(fixed, [export.APNG_DELAY_MS] * len(MOVES) + [export.APNG_END_MS])
        timed = frame_delays(export.export("apng", state, opts(scope="game", move_times=True)))
        # Bild n steht, bis Halbzug n gespielt ist
        self.assertEqual(timed, [500 * (ply + 1) for ply in range(len(MOVES))] + [export.APNG_END_MS])

    def test_long_think_time_fits_into_frame_control(self):
        self.assertEqual(export._delay(90_000), (9000, 100))
        self.assertEqual(export._delay(10), (export.APNG_MIN_MS, 1000))

    def test_pgn_move_times_optional(self):
        state = sample()
        state.times = {0: 3500, 1: 61000}
        with_times = export.export("pgn", state, opts(scope="game", move_times=True))
        self.assertIn("[%emt 0:00:03.5]", with_times)
        self.assertIn("[%emt 0:01:01]", with_times)
        self.assertNotIn("%emt", export.export("pgn", state, opts(scope="game")))
        without_evals = export.export("pgn", state, opts(scope="game", move_times=True, evals=False))
        self.assertNotIn("%wp", without_evals)
        self.assertIn("%emt", without_evals)


@unittest.skipUnless(export.webp_available(), "Pillow mit WebP fehlt")
class WebpTest(unittest.TestCase):
    def open(self, data):
        from PIL import Image
        return Image.open(io.BytesIO(data))

    def test_position_is_still_image_like_png(self):
        image = self.open(export.export("webp", sample(), opts(plies=8)))
        self.assertEqual(image.format, "WEBP")
        self.assertFalse(getattr(image, "is_animated", False))
        png = self.open(export.export("png", sample(), opts(plies=8)))
        self.assertEqual(image.size, png.size)
        self.assertEqual(image.mode, "RGBA")  # durchsichtiger Rand bleibt durchsichtig

    def test_game_is_animation_with_same_frames_as_apng(self):
        state = sample()
        state.times = {ply: 300 * (ply + 1) for ply in range(len(MOVES))}
        o = opts(scope="game", move_times=True)
        webp = self.open(export.export("webp", state, o))
        apng = self.open(export.export("apng", state, o))
        self.assertEqual(webp.n_frames, len(MOVES) + 1)
        delays = []
        for index in range(webp.n_frames):
            webp.seek(index)
            webp.load()
            apng.seek(index)
            delays.append(webp.info["duration"])
            self.assertEqual(webp.convert("RGB").tobytes(), apng.convert("RGB").tobytes(), f"Bild {index}")
        self.assertEqual(delays, [300 * (ply + 1) for ply in range(len(MOVES))] + [export.APNG_END_MS])

    def test_filename_by_scope(self):
        self.assertRegex(export.filename("webp", sample(), opts()), r"^stellung-.*\.webp$")
        self.assertRegex(export.filename("webp", sample(), opts(scope="game")), r"^partie-animiert-.*\.webp$")


class MotionTest(unittest.TestCase):
    def test_castling_moves_king_and_rook(self):
        board = chess.Board("r3k2r/8/8/8/8/8/8/R3K2R w KQkq - 0 1")
        motion = export.move_motion(board, chess.Move.from_uci("e1g1"))
        self.assertEqual([(src, dst) for _p, src, dst in motion["movers"]],
                         [(chess.E1, chess.G1), (chess.H1, chess.F1)])
        self.assertIsNone(motion["captured"])

    def test_en_passant_captures_the_pawn_beside(self):
        board = chess.Board("4k3/8/8/3pP3/8/8/8/4K3 w - d6 0 1")
        motion = export.move_motion(board, chess.Move.from_uci("e5d6"))
        self.assertEqual(motion["captured"], (chess.Piece(chess.PAWN, chess.BLACK), chess.D5))

    def test_timeline_holds_then_glides(self):
        timeline, end = export._video_timeline(sample(), opts(scope="game"))
        steps = round(export.VIDEO_MOVE_MS * export.VIDEO_FPS / 1000)
        self.assertEqual(len(timeline), len(MOVES) * (1 + steps) + 1)
        self.assertEqual(end, len(MOVES) * export.APNG_DELAY_MS + export.APNG_END_MS)
        starts = [start for _d, start in timeline]
        self.assertEqual(starts, sorted(set(starts)))  # streng steigend
        # erster Zug: ruht, dann gleitet er in den letzten VIDEO_MOVE_MS vor 1,5 s
        self.assertEqual(starts[0], 0)
        self.assertEqual(starts[1], export.APNG_DELAY_MS - export.VIDEO_MOVE_MS)
        self.assertEqual(starts[1 + steps], export.APNG_DELAY_MS)
        gliding = timeline[1][0]
        self.assertIsNone(gliding.badge)
        self.assertLess(gliding._anim["progress"], 1)
        self.assertEqual(timeline[steps][0]._anim["progress"], 1)


def _probe(data, suffix):
    """(Codec, Breite, Höhe, Bildzahl, Zeit des letzten Bilds in s) eines Videos, gelesen mit ffprobe."""
    with tempfile.NamedTemporaryFile(suffix=suffix) as fh:
        fh.write(data)
        fh.flush()
        info = subprocess.run(["ffprobe", "-v", "error", "-select_streams", "v:0", "-count_frames",
                               "-show_entries", "stream=codec_name,width,height,nb_read_frames",
                               "-of", "default=nw=1", fh.name], capture_output=True, text=True).stdout
        times = subprocess.run(["ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries",
                                "frame=pts_time", "-of", "csv=p=0", fh.name], capture_output=True, text=True).stdout
    fields = dict(line.split("=", 1) for line in info.split())
    return (fields["codec_name"], int(fields["width"]), int(fields["height"]), int(fields["nb_read_frames"]),
            float(times.split()[-1]))


@unittest.skipUnless(shutil.which("ffprobe") and not export.video_problem("webm") and not export.video_problem("mp4"),
                     "ffmpeg mit libvpx-vp9 und libx264 fehlt")
class VideoTest(unittest.TestCase):
    def test_webm_and_mp4(self):
        steps = round(export.VIDEO_MOVE_MS * export.VIDEO_FPS / 1000)
        frames = len(MOVES) * (1 + steps) + 1
        end = (len(MOVES) * export.APNG_DELAY_MS + export.APNG_END_MS) / 1000
        last_shown = end - export.APNG_END_MS / 1000  # Schlussstellung beginnt hier, steht bis ``end``
        for fmt, codec in (("webm", "vp9"), ("mp4", "h264")):
            codec_name, width, height, count, last = _probe(
                export.export(fmt, sample(), opts(scope="game")), "." + fmt)
            self.assertEqual(codec_name, codec)
            self.assertEqual(width, export.APNG_WIDTH)
            self.assertEqual(height % 2, 0)
            self.assertGreaterEqual(count, frames, fmt)  # lange Ruhe wird in Stücken wiederholt
            self.assertGreaterEqual(last, last_shown - 0.01, fmt)

    def test_duration_follows_move_times(self):
        state = sample()
        state.times = {ply: 2000 for ply in range(len(MOVES))}
        data = export.export("webm", state, opts(scope="game", move_times=True))
        with tempfile.NamedTemporaryFile(suffix=".webm") as fh:
            fh.write(data)
            fh.flush()
            duration = float(subprocess.run(["ffprobe", "-v", "error", "-show_entries", "format=duration",
                                             "-of", "csv=p=0", fh.name], capture_output=True, text=True).stdout)
        self.assertAlmostEqual(duration, (len(MOVES) * 2000 + export.APNG_END_MS) / 1000, delta=0.1)


class FfmpegLookupTest(unittest.TestCase):
    def test_configured_path_wins_and_must_exist(self):
        self.assertIsNone(export.find_ffmpeg("/gibt/es/nicht/ffmpeg"))
        self.assertIn("/gibt/es/nicht/ffmpeg", export.video_problem("webm", "/gibt/es/nicht/ffmpeg"))
        with self.assertRaises(export.ExportError):
            export.export("mp4", sample(), opts(scope="game", ffmpeg="/gibt/es/nicht/ffmpeg"))

    def test_without_ffmpeg_in_path(self):
        from unittest import mock
        with mock.patch("shutil.which", return_value=None):
            self.assertIsNone(export.find_ffmpeg())
            self.assertIn("Einstellungen", export.video_problem("webm"))


class MoveTimesTest(unittest.TestCase):
    def test_format_time(self):
        self.assertEqual([notation.format_time(ms) for ms in (800, 9940, 9960, 42000, 65000, 3725000)],
                         ["0,8 s", "9,9 s", "10 s", "42 s", "1:05", "1:02:05"])

    def test_html_shows_times_only_when_asked(self):
        state = sample()
        state.times = {0: 3500, 3: 65000}
        page = export.export("html", state, opts(scope="game", move_times=True))
        self.assertIn('<small class="t" title="Bedenkzeit">3,5 s</small>', page)
        self.assertIn(">1:05</small>", page)
        self.assertEqual(page.count('class="t"'), 2)  # nur Züge mit bekannter Zeit
        self.assertNotIn('class="t"', export.export("html", state, opts(scope="game")))

    @unittest.skipUnless(shutil.which("pdftotext"), "pdftotext fehlt")
    def test_pdf_shows_times_only_when_asked(self):
        state = sample()
        state.times = {0: 3500, 3: 65000}

        def text(**kw):
            with tempfile.NamedTemporaryFile(suffix=".pdf") as fh:
                fh.write(export.export("pdf", state, opts(scope="game", **kw)))
                fh.flush()
                return subprocess.run(["pdftotext", fh.name, "-"], capture_output=True, text=True).stdout

        self.assertIn("3,5 s", text(move_times=True))
        self.assertIn("1:05", text(move_times=True))
        self.assertNotIn("3,5 s", text())

    def test_saved_times_come_back(self):
        state = sample()
        state.times = {0: 1200, 3: 45600}
        self.assertEqual(savegames.from_pgn(savegames.to_pgn(state)).times, {0: 1200, 3: 45600})
        self.assertEqual(state.truncated(1).times, {0: 1200})

    def test_times_from_lichess_clock(self):
        pgn = ('[TimeControl "180+2"]\n\n'
               "1. e4 { [%clk 0:03:00] } e5 { [%clk 0:03:00] } "
               "2. Nf3 { [%clk 0:02:55] } Nc6 { [%clk 0:02:51.5] } *")
        times = savegames.from_pgn(pgn).times
        # Restzeit davor − Restzeit danach + Zuschlag
        self.assertEqual(times, {0: 2000, 1: 2000, 2: 7000, 3: 10500})

    def test_emt_wins_over_clock(self):
        pgn = '1. e4 { [%clk 0:03:00] [%emt 0:00:04] } *'
        self.assertEqual(savegames.from_pgn(pgn).times, {0: 4000})

    def test_no_clock_no_times(self):
        self.assertEqual(savegames.from_pgn("1. e4 e5 *").times, {})


class MetaTest(unittest.TestCase):
    def test_filename(self):
        self.assertRegex(export.filename("pdf", sample(), opts(scope="game")), r"^partie-\d{4}-\d\d-\d\d\.pdf$")
        self.assertRegex(export.filename("png", sample(), opts(scope="game")), r"^stellung-.*\.png$")
        self.assertRegex(export.filename("apng", sample(), opts()), r"^partie-animiert-.*\.png$")

    def test_every_format_has_writer(self):
        for fmt in export.FORMATS:
            if (fmt == "pdf-latex" or fmt == "webp" and not export.webp_available()
                    or fmt in export.VIDEO_CODECS and export.video_problem(fmt)):
                continue
            for scope in export.FORMATS[fmt].scopes:
                self.assertTrue(export.export(fmt, sample(), opts(scope=scope, plies=5)))


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