"""Tests for mirror configuration module."""

import os
from pathlib import Path
from multi_lang_build.mirror.config import (
    get_mirror_config,
    apply_mirror_environment,
    reset_mirror_environment,
    get_all_mirror_names,
    validate_mirror_config,
    MIRROR_CONFIGS,
    # Go mirror constants
    GO_PROXY_GOPROXY_CN,
    GO_PROXY_GOPROXY_IO,
    GO_PROXY_GOVIP_CN,
    GO_SUMDB_GOLANG,
    GO_SUMDB_GOLANG_GOOGLE_CN,
    DEFAULT_GO_MIRROR,
    # Pip mirror constants
    PYPI_MIRROR_TSINGHUA,
    PYPI_MIRROR_ALIYUN,
    PYPI_MIRROR_DOUBAN,
    PYPI_MIRROR_HUAWEI,
    PYPI_MIRROR_NETEASE,
    DEFAULT_PIP_MIRROR,
    # NPM mirror constants
    NPM_REGISTRY_NPMMIRROR,
)


class TestMirrorConstants:
    """Tests for mirror constants."""

    def test_go_mirror_constants(self) -> None:
        """Test Go mirror constants are defined correctly."""
        assert GO_PROXY_GOPROXY_CN == "https://goproxy.cn"
        assert GO_PROXY_GOPROXY_IO == "https://goproxy.io"
        assert GO_PROXY_GOVIP_CN == "https://goproxy.vip.cn"
        assert GO_SUMDB_GOLANG == "sum.golang.org"
        assert GO_SUMDB_GOLANG_GOOGLE_CN == "sum.golang.google.cn"
        assert DEFAULT_GO_MIRROR == "https://goproxy.cn"

    def test_pip_mirror_constants(self) -> None:
        """Test Pip mirror constants are defined correctly."""
        assert PYPI_MIRROR_TSINGHUA == "https://pypi.tuna.tsinghua.edu.cn"
        assert PYPI_MIRROR_ALIYUN == "https://mirrors.aliyun.com/pypi/simple"
        assert PYPI_MIRROR_DOUBAN == "https://pypi.doubanio.com/simple"
        assert PYPI_MIRROR_HUAWEI == "https://repo.huaweicloud.com/repository/pypi/simple"
        assert PYPI_MIRROR_NETEASE == "https://mirrors.163.com/pypi/simple"
        assert DEFAULT_PIP_MIRROR == "https://pypi.tuna.tsinghua.edu.cn"

    def test_npm_mirror_constants(self) -> None:
        """Test NPM mirror constants are defined correctly."""
        assert NPM_REGISTRY_NPMMIRROR == "https://registry.npmmirror.com"


class TestMirrorConfigs:
    """Tests for mirror configurations."""

    def test_go_mirror_configs(self) -> None:
        """Test Go mirror configurations are present."""
        go_config = get_mirror_config("go")
        assert go_config is not None
        assert "goproxy.cn" in go_config["url"]
        
        go_qiniu = get_mirror_config("go_qiniu")
        assert go_qiniu is not None
        assert "goproxy.io" in go_qiniu["url"]
        
        go_vip = get_mirror_config("go_vip")
        assert go_vip is not None
        assert "goproxy.vip.cn" in go_vip["url"]

    def test_pip_mirror_configs(self) -> None:
        """Test Pip mirror configurations are present."""
        pip_config = get_mirror_config("pip")
        assert pip_config is not None
        assert "pypi.tuna.tsinghua.edu.cn" in pip_config["url"]
        
        pip_aliyun = get_mirror_config("pip_aliyun")
        assert pip_aliyun is not None
        assert "mirrors.aliyun.com" in pip_aliyun["url"]
        
        pip_douban = get_mirror_config("pip_douban")
        assert pip_douban is not None
        assert "pypi.doubanio.com" in pip_douban["url"]
        
        pip_huawei = get_mirror_config("pip_huawei")
        assert pip_huawei is not None
        assert "repo.huaweicloud.com" in pip_huawei["url"]

    def test_get_mirror_config(self) -> None:
        """Test getting mirror configuration for known package managers."""
        npm_config = get_mirror_config("npm")
        assert npm_config is not None
        assert "npmmirror.com" in npm_config["url"]
        
        go_config = get_mirror_config("go")
        assert go_config is not None
        assert "goproxy.cn" in go_config["url"]
        
        pip_config = get_mirror_config("pip")
        assert pip_config is not None
        assert "pypi.tuna.tsinghua.edu.cn" in pip_config["url"]

    def test_get_mirror_config_unknown(self) -> None:
        """Test getting mirror configuration for unknown package manager."""
        config = get_mirror_config("unknown_package_manager")
        assert config is None


class TestMirrorEnvironment:
    """Tests for mirror environment variables."""

    def test_apply_go_mirror_environment(self) -> None:
        """Test applying Go mirror environment variables."""
        base_env: dict[str, str] = {"PATH": "/usr/bin"}
        
        updated_env = apply_mirror_environment("go", base_env)
        
        assert updated_env["PATH"] == "/usr/bin"
        assert "GOPROXY" in updated_env
        assert "GOSUMDB" in updated_env
        assert updated_env["GOPROXY"] == "https://goproxy.cn,direct"

    def test_apply_go_qiniu_mirror_environment(self) -> None:
        """Test applying Go qiniu mirror environment variables."""
        base_env: dict[str, str] = {}
        
        updated_env = apply_mirror_environment("go_qiniu", base_env)
        
        assert "GOPROXY" in updated_env
        assert "goproxy.io" in updated_env["GOPROXY"]

    def test_apply_pip_mirror_environment(self) -> None:
        """Test applying pip mirror environment variables."""
        base_env: dict[str, str] = {}
        
        updated_env = apply_mirror_environment("pip", base_env)
        
        assert updated_env["PIP_INDEX_URL"] == "https://pypi.tuna.tsinghua.edu.cn/simple"
        assert updated_env["PIP_TRUSTED_HOST"] == "pypi.tuna.tsinghua.edu.cn"

    def test_apply_pip_aliyun_mirror_environment(self) -> None:
        """Test applying pip aliyun mirror environment variables."""
        base_env: dict[str, str] = {}
        
        updated_env = apply_mirror_environment("pip_aliyun", base_env)
        
        assert "mirrors.aliyun.com" in updated_env["PIP_INDEX_URL"]
        assert "mirrors.aliyun.com" in updated_env["PIP_TRUSTED_HOST"]

    def test_reset_mirror_environment(self) -> None:
        """Test removing mirror environment variables."""
        base_env: dict[str, str] = {
            "PATH": "/usr/bin",
            "GOPROXY": "https://goproxy.cn,direct",
            "GOSUMDB": "sum.golang.google.cn",
        }
        
        reset_env = reset_mirror_environment("go", base_env)
        
        assert reset_env["PATH"] == "/usr/bin"
        assert "GOPROXY" not in reset_env
        assert "GOSUMDB" not in reset_env


class TestMirrorList:
    """Tests for mirror list functions."""

    def test_get_all_mirror_names(self) -> None:
        """Test getting all available mirror names."""
        mirrors = get_all_mirror_names()
        
        assert isinstance(mirrors, list)
        assert "npm" in mirrors
        assert "pnpm" in mirrors
        assert "go" in mirrors
        assert "go_qiniu" in mirrors
        assert "go_vip" in mirrors
        assert "pip" in mirrors
        assert "pip_aliyun" in mirrors
        assert "pip_douban" in mirrors
        assert "pip_huawei" in mirrors
        assert len(mirrors) >= 10


class TestMirrorValidation:
    """Tests for mirror validation."""

    def test_validate_mirror_config(self) -> None:
        """Test validating mirror configurations."""
        valid_config = {
            "name": "Test Mirror",
            "url": "https://example.com",
            "environment_prefix": "TEST",
            "environment_variables": {"TEST_VAR": "value"},
        }
        
        assert validate_mirror_config(valid_config) is True
        
        invalid_config = {
            "name": "",
            "url": "invalid-url",
            "environment_prefix": "TEST",
            "environment_variables": {},
        }
        
        assert validate_mirror_config(invalid_config) is False

    def test_validate_mirror_http_url(self) -> None:
        """Test that HTTP URLs are accepted."""
        valid_config = {
            "name": "Test Mirror",
            "url": "http://example.com",
            "environment_prefix": "TEST",
            "environment_variables": {"TEST_VAR": "value"},
        }
        
        assert validate_mirror_config(valid_config) is True

    def test_validate_mirror_https_url(self) -> None:
        """Test that HTTPS URLs are accepted."""
        valid_config = {
            "name": "Test Mirror",
            "url": "https://example.com",
            "environment_prefix": "TEST",
            "environment_variables": {"TEST_VAR": "value"},
        }
        
        assert validate_mirror_config(valid_config) is True


class TestMirrorConfigStructure:
    """Tests for mirror configuration structure."""

    def test_mirror_config_structure(self) -> None:
        """Test that all mirror configurations have required fields."""
        for name, config in MIRROR_CONFIGS.items():
            assert "name" in config, f"Missing 'name' in {name}"
            assert "url" in config, f"Missing 'url' in {name}"
            assert "environment_prefix" in config, f"Missing 'environment_prefix' in {name}"
            assert "environment_variables" in config, f"Missing 'environment_variables' in {name}"
            assert isinstance(config["environment_variables"], dict)
            assert config["url"].startswith("http")

    def test_all_go_mirror_configs_have_sumdb(self) -> None:
        """Test that all Go mirror configurations have GOSUMDB set."""
        go_mirrors = ["go", "go_qiniu", "go_vip"]
        
        for mirror_name in go_mirrors:
            config = get_mirror_config(mirror_name)
            assert config is not None
            env_vars = config.get("environment_variables", {})
            assert "GOSUMDB" in env_vars, f"Missing GOSUMDB in {mirror_name}"
