"""Nachbesprechen: Zeitleiste und PGN in der Opus-Datei."""

import os
import shutil
import tempfile
import unittest

import chess

from schach import recording

M = chess.Move.from_uci


class TimelineTest(unittest.TestCase):
    def test_steps_jumps_and_shapes_round_trip(self):
        timeline = recording.Timeline()
        timeline.show(0, (), ())
        timeline.show(1200, (M("e2e4"),), ())
        timeline.show(1200, (M("e2e4"),), ())  # unverändert: kein Eintrag
        timeline.show(2000, (M("e2e4"), M("e7e5")), ((chess.F7, chess.F7, "red"), (chess.G1, chess.F3, "green")))
        timeline.show(3000, (M("e2e4"),), ((chess.F7, chess.F7, "red"), (chess.G1, chess.F3, "green")))
        timeline.show(4000, (M("d2d4"), M("d7d5")), ())
        text = timeline.encode()
        self.assertEqual(text, "0 =;1200 >e2e4;2000 >e7e5;2000 #Rf7,Gg1f3;3000 <;4000 =d2d4,d7d5;4000 #")
        frames = recording.decode(text)
        self.assertEqual(recording.at(frames, 2500), ((M("e2e4"), M("e7e5")),
                                                      ((chess.F7, chess.F7, "red"), (chess.G1, chess.F3, "green"))))
        self.assertEqual(recording.at(frames, 3500)[0], (M("e2e4"),))
        self.assertEqual(recording.at(frames, 9999), ((M("d2d4"), M("d7d5")), ()))
        self.assertEqual(recording.at(frames, 0), ((), ()))


@unittest.skipUnless(shutil.which("gst-launch-1.0"), "GStreamer fehlt")
class OpusTest(unittest.TestCase):
    def setUp(self):
        import subprocess
        self.dir = tempfile.mkdtemp()
        self.path = os.path.join(self.dir, "ton.opus")
        subprocess.run(["gst-launch-1.0", "-q", "audiotestsrc", "num-buffers=50", "!", "audioconvert", "!",
                        "opusenc", "!", "oggmux", "!", "filesink", f"location={self.path}"], check=True)

    def tearDown(self):
        shutil.rmtree(self.dir)

    def test_pgn_survives_and_audio_stays(self):
        with open(self.path, "rb") as f:
            original = f.read()
        pgn = '[Event "Test"]\n[Replay "0 =;500 >e2e4"]\n\n1. e4 { Idee } *\n'
        for text in (pgn, pgn * 2000):  # auch über mehrere Ogg-Seiten
            data = recording.write_pgn(original, text)
            self.assertEqual(recording.read_tags(data)["PGN"], text)
            audio = [body for _head, _lacing, body in recording._pages(original)[2:]]
            self.assertEqual([body for _head, _lacing, body in recording._pages(data)][-len(audio):], audio)


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


@unittest.skipUnless(shutil.which("ffmpeg"), "ffmpeg fehlt")
class WebmTest(unittest.TestCase):
    def test_pgn_from_matroska_tag(self):
        import subprocess
        pgn = '[Event "Test"]\n[Replay "0 =;500 >e2e4"]\n\n1. e4 { Idee } *\n'
        with tempfile.TemporaryDirectory() as folder:
            path = os.path.join(folder, "video.webm")
            subprocess.run(["ffmpeg", "-v", "error", "-y", "-f", "lavfi", "-i", "sine=d=1", "-f", "lavfi", "-i",
                            "color=s=64x64:d=1", "-c:a", "libopus", "-c:v", "libvpx-vp9", "-shortest",
                            "-metadata", f"PGN={pgn}", path], check=True)
            self.assertEqual(recording.read_pgn(path), pgn)


@unittest.skipUnless(shutil.which("ffmpeg") and shutil.which("gst-launch-1.0"), "ffmpeg oder GStreamer fehlt")
class ReviewVideoTest(unittest.TestCase):
    def test_video_with_sound_and_pgn(self):
        import io
        import subprocess
        import chess.pgn
        from schach import export, savegames
        board = chess.Board()
        for san in ("e4", "e5", "Bc4"):
            board.push_san(san)
        state = savegames.GameState(board=board, human=chess.WHITE, elo=600)
        with tempfile.TemporaryDirectory() as folder:
            audio = os.path.join(folder, "ton.opus")
            subprocess.run(["gst-launch-1.0", "-q", "audiotestsrc", "num-buffers=100", "!", "audioconvert", "!",
                            "opusenc", "!", "oggmux", "!", "filesink", f"location={audio}"], check=True)
            with open(audio, "rb") as f:
                length = recording.duration_ms(f.read())
            self.assertGreater(length, 1500)
            timeline = "0 =;300 >e2e4;900 >e7e5;1200 #Rf7;1500 =e2e4"
            pgn = savegames.to_pgn(state).replace("\n\n", f'\n[Replay "{timeline}"]\n\n', 1)
            frames = recording.decode(chess.pgn.read_headers(io.StringIO(pgn))["Replay"])
            for fmt in ("webm", "mp4"):  # beide öffnet die App wieder als Nachbesprechung
                data = export.review_video(fmt, state, frames, length, audio, pgn, export.Options())
                path = os.path.join(folder, f"video.{fmt}")
                with open(path, "wb") as f:
                    f.write(data)
                self.assertEqual(recording.read_pgn(path), pgn)
                streams = subprocess.run(["ffprobe", "-v", "error", "-show_entries", "stream=codec_type", "-of", "csv=p=0",
                                          path], capture_output=True, text=True).stdout.split()
                self.assertEqual(sorted(streams), ["audio", "video"])
