from __future__ import annotations

import json
import os
from pathlib import Path
import sys
import tempfile
import unittest

from click.testing import CliRunner


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 SubtitleDirectoryCliTests(unittest.TestCase):
    def setUp(self):
        self.tempdir = tempfile.TemporaryDirectory()
        self.home_dir = Path(self.tempdir.name) / "home"
        self.home_dir.mkdir()
        self.database_path = Path(self.tempdir.name) / "test.db"

    def tearDown(self):
        self.tempdir.cleanup()

    def write_config(self, data: dict) -> None:
        config_dir = self.home_dir / ".local" / "etc"
        config_dir.mkdir(parents=True, exist_ok=True)
        (config_dir / "ffx.json").write_text(json.dumps(data), encoding="utf-8")

    def invoke_convert(self, *args: str):
        runner = CliRunner()
        return runner.invoke(
            cli.ffx,
            [
                "--database-file",
                str(self.database_path),
                "convert",
                "--no-tmdb",
                *args,
            ],
            env={**os.environ, "HOME": str(self.home_dir)},
        )

    def test_subtitle_prefix_without_directory_or_default_fails(self):
        result = self.invoke_convert("--subtitle-prefix", "dball")

        self.assertNotEqual(0, result.exit_code)
        self.assertIn("no --subtitle-directory was provided", result.output)
        self.assertIn("no subtitlesDirectory default is configured", result.output)

    def test_subtitle_prefix_without_directory_fails_when_configured_subdir_is_missing(self):
        subtitles_base_dir = self.home_dir / ".local" / "var" / "sync" / "subtitles"
        subtitles_base_dir.mkdir(parents=True, exist_ok=True)
        self.write_config({"subtitlesDirectory": "~/.local/var/sync/subtitles"})

        result = self.invoke_convert("--subtitle-prefix", "dball")

        self.assertNotEqual(0, result.exit_code)
        self.assertIn("resolved subtitle directory does not exist", result.output)
        self.assertIn(str(subtitles_base_dir / "dball"), result.output)

    def test_explicit_subtitle_directory_wins_over_missing_default(self):
        explicit_subtitle_directory = self.home_dir / "manual-subtitles"
        explicit_subtitle_directory.mkdir(parents=True, exist_ok=True)

        result = self.invoke_convert(
            "--subtitle-directory",
            str(explicit_subtitle_directory),
            "--subtitle-prefix",
            "dball",
        )

        self.assertEqual(0, result.exit_code, result.output)


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