"""Tests for qpip.core."""

from __future__ import annotations

import unittest

from qpip.core import (
    DEFAULT_MIRROR,
    MIRRORS,
    build_pip_command,
    get_default_mirror,
    normalize_mirror_name,
    should_inject_mirror,
)


class NormalizeMirrorNameTests(unittest.TestCase):
    def test_supports_aliases(self) -> None:
        self.assertEqual(normalize_mirror_name("aliyun"), "ali")
        self.assertEqual(normalize_mirror_name("TUNA"), "tsinghua")

    def test_rejects_unknown_mirror(self) -> None:
        with self.assertRaises(ValueError):
            normalize_mirror_name("unknown")


class GetDefaultMirrorTests(unittest.TestCase):
    def test_invalid_environment_value_falls_back(self) -> None:
        mirror, warning = get_default_mirror({"QPIP_DEFAULT_MIRROR": "bad"})

        self.assertEqual(mirror, DEFAULT_MIRROR)
        self.assertIn("falling back", warning)


class MirrorInjectionTests(unittest.TestCase):
    def test_install_injects_index_url(self) -> None:
        command = build_pip_command(["install", "requests"], mirror="ali", python_executable="python")

        self.assertEqual(
            command,
            ["python", "-m", "pip", "install", "requests", "-i", MIRRORS["ali"]],
        )

    def test_explicit_index_url_disables_injection(self) -> None:
        command = build_pip_command(
            ["install", "requests", "--index-url", "https://example.com/simple"],
            mirror="ali",
            python_executable="python",
        )

        self.assertEqual(
            command,
            [
                "python",
                "-m",
                "pip",
                "install",
                "requests",
                "--index-url",
                "https://example.com/simple",
            ],
        )

    def test_non_network_commands_do_not_inject_index_url(self) -> None:
        self.assertFalse(should_inject_mirror(["list"]))
        self.assertFalse(should_inject_mirror(["config", "list"]))

    def test_empty_args_raise(self) -> None:
        with self.assertRaises(ValueError):
            build_pip_command([], mirror="ali")


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