from __future__ import annotations

from pathlib import Path
import sys
import tempfile
import unittest

import click


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 import cli  # noqa: E402


class StaticConfig:
    def __init__(self, subtitles_directory: str = ""):
        self._subtitles_directory = subtitles_directory

    def getSubtitlesDirectoryPath(self):
        return self._subtitles_directory


class UnmuxOutputDirectoryTests(unittest.TestCase):
    def test_subtitles_only_with_label_uses_configured_subtitles_base_directory(self):
        with tempfile.TemporaryDirectory() as tempdir:
            context = {
                "config": StaticConfig(str(Path(tempdir) / "subtitles")),
            }

            resolved_output_directory, should_create = cli.resolveUnmuxOutputDirectory(
                context,
                "",
                True,
                "dball",
            )

        self.assertEqual(str(Path(tempdir) / "subtitles" / "dball"), resolved_output_directory)
        self.assertTrue(should_create)

    def test_explicit_output_directory_keeps_existing_behavior(self):
        with tempfile.TemporaryDirectory() as tempdir:
            context = {
                "config": StaticConfig(str(Path(tempdir) / "subtitles")),
            }
            explicit_output_directory = str(Path(tempdir) / "manual")

            resolved_output_directory, should_create = cli.resolveUnmuxOutputDirectory(
                context,
                explicit_output_directory,
                True,
                "dball",
            )

        self.assertEqual(explicit_output_directory, resolved_output_directory)
        self.assertFalse(should_create)

    def test_subtitles_only_without_label_keeps_existing_behavior(self):
        context = {
            "config": StaticConfig("/tmp/subtitles"),
        }

        resolved_output_directory, should_create = cli.resolveUnmuxOutputDirectory(
            context,
            "",
            True,
            "",
        )

        self.assertEqual("", resolved_output_directory)
        self.assertFalse(should_create)

    def test_subtitles_only_with_label_requires_configured_default_when_output_directory_is_missing(self):
        context = {
            "config": StaticConfig(""),
        }

        with self.assertRaises(click.ClickException) as caught:
            cli.resolveUnmuxOutputDirectory(
                context,
                "",
                True,
                "dball",
            )

        self.assertIn("subtitlesDirectory default", str(caught.exception))


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