from __future__ import annotations

from pathlib import Path
import sys
import tempfile
import unittest


SRC_ROOT = Path(__file__).resolve().parents[2] / "src"

if str(SRC_ROOT) not in sys.path:
    sys.path.insert(0, str(SRC_ROOT))


from ffx.logging_utils import get_ffx_logger  # noqa: E402
from ffx.media_descriptor import MediaDescriptor  # noqa: E402
from ffx.track_descriptor import TrackDescriptor  # noqa: E402
from ffx.track_disposition import TrackDisposition  # noqa: E402
from ffx.track_type import TrackType  # noqa: E402


class MediaDescriptorImportSubtitlesTests(unittest.TestCase):
    def make_descriptor(self) -> MediaDescriptor:
        return MediaDescriptor(
            context={"logger": get_ffx_logger()},
            track_descriptors=[
                TrackDescriptor(
                    index=3,
                    source_index=3,
                    sub_index=0,
                    track_type=TrackType.SUBTITLE,
                    tags={"language": "eng", "title": "DB Subtitle"},
                    disposition_set={TrackDisposition.DEFAULT},
                )
            ],
        )

    def test_import_subtitles_preserves_target_dispositions_when_requested(self):
        descriptor = self.make_descriptor()

        with tempfile.TemporaryDirectory() as tmpdir:
            sidecar_path = Path(tmpdir) / "dball_S01E01_3_deu_FOR.vtt"
            sidecar_path.write_text("WEBVTT\n\n", encoding="utf-8")

            descriptor.importSubtitles(
                tmpdir,
                "dball",
                season=1,
                episode=1,
                preserve_dispositions=True,
            )

        track = descriptor.getSubtitleTracks()[0]
        self.assertEqual(str(sidecar_path), track.getExternalSourceFilePath())
        self.assertEqual("deu", track.getTags()["language"])
        self.assertEqual({TrackDisposition.DEFAULT}, track.getDispositionSet())

    def test_import_subtitles_uses_sidecar_dispositions_by_default(self):
        descriptor = self.make_descriptor()

        with tempfile.TemporaryDirectory() as tmpdir:
            sidecar_path = Path(tmpdir) / "dball_S01E01_3_deu_FOR.vtt"
            sidecar_path.write_text("WEBVTT\n\n", encoding="utf-8")

            descriptor.importSubtitles(
                tmpdir,
                "dball",
                season=1,
                episode=1,
            )

        track = descriptor.getSubtitleTracks()[0]
        self.assertEqual(str(sidecar_path), track.getExternalSourceFilePath())
        self.assertEqual("deu", track.getTags()["language"])
        self.assertEqual({TrackDisposition.FORCED}, track.getDispositionSet())


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