"""Tests for qpip.cli."""

from __future__ import annotations

import io
import unittest
from contextlib import redirect_stdout

from qpip.cli import CLIUsageError, HELP_TEXT, main, parse_cli_args


class ParseCliArgsTests(unittest.TestCase):
    def test_supports_positional_mirror(self) -> None:
        options, warning = parse_cli_args(["tsinghua", "install", "numpy"])

        self.assertIsNone(warning)
        self.assertEqual(options.mirror, "tsinghua")
        self.assertEqual(options.pip_args, ("install", "numpy"))

    def test_supports_named_mirror(self) -> None:
        options, _ = parse_cli_args(["--mirror", "douban", "install", "pandas"])

        self.assertEqual(options.mirror, "douban")
        self.assertEqual(options.pip_args, ("install", "pandas"))

    def test_respects_separator_for_pip_options(self) -> None:
        options, _ = parse_cli_args(["--", "--version"])

        self.assertEqual(options.pip_args, ("--version",))

    def test_detects_conflicting_mirrors(self) -> None:
        with self.assertRaises(CLIUsageError):
            parse_cli_args(["ali", "--mirror", "douban", "install", "requests"])

    def test_recognizes_qpip_flags_before_pip_args(self) -> None:
        options, _ = parse_cli_args(["--dry-run", "--list-mirrors"])

        self.assertTrue(options.dry_run)
        self.assertTrue(options.list_mirrors)
        self.assertEqual(options.pip_args, ())

    def test_help_text_is_localized_to_chinese(self) -> None:
        self.assertIn("使用更快的软件包镜像运行 pip", HELP_TEXT)
        self.assertIn("用法:", HELP_TEXT)
        self.assertIn("说明:", HELP_TEXT)
        self.assertIn("qpip i requests", HELP_TEXT)

    def test_dry_run_supports_install_alias(self) -> None:
        buffer = io.StringIO()

        with redirect_stdout(buffer):
            exit_code = main(["--dry-run", "i", "requests"])

        self.assertEqual(exit_code, 0)
        self.assertIn("-m pip install requests", buffer.getvalue())


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