"""Mirror configuration for domestic acceleration."""

from typing import TypedDict, Literal
from pathlib import Path


# ============================================================================
# Constants for mainstream domestic mirrors
# ============================================================================

# NPM/PNPM mirrors
NPM_REGISTRY_NPMMIRROR: Literal["https://registry.npmmirror.com"] = "https://registry.npmmirror.com"
NPM_REGISTRY_TAOBAO: Literal["https://registry.npmmirror.com"] = "https://registry.npmmirror.com"  # Taobao mirrors npmmirror

# Go mirrors (including Qiniu cloud)
GO_PROXY_GOPROXY_CN: Literal["https://goproxy.cn"] = "https://goproxy.cn"
GO_PROXY_GOPROXY_IO: Literal["https://goproxy.io"] = "https://goproxy.io"
GO_PROXY_GOVIP_CN: Literal["https://goproxy.vip.cn"] = "https://goproxy.vip.cn"
GO_PROXY_FASTGOPROXY: Literal["https://goproxy.cn,direct"] = "https://goproxy.cn,direct"

# Go sumdb mirrors
GO_SUMDB_GOLANG: Literal["sum.golang.org"] = "sum.golang.org"
GO_SUMDB_GOLANG_GOOGLE_CN: Literal["sum.golang.google.cn"] = "sum.golang.google.cn"

# PyPI/Pip mirrors
PYPI_MIRROR_TSINGHUA: Literal["https://pypi.tuna.tsinghua.edu.cn"] = "https://pypi.tuna.tsinghua.edu.cn"
PYPI_MIRROR_ALIYUN: Literal["https://mirrors.aliyun.com/pypi/simple"] = "https://mirrors.aliyun.com/pypi/simple"
PYPI_MIRROR_DOUBAN: Literal["https://pypi.doubanio.com/simple"] = "https://pypi.doubanio.com/simple"
PYPI_MIRROR_HUAWEI: Literal["https://repo.huaweicloud.com/repository/pypi/simple"] = "https://repo.huaweicloud.com/repository/pypi/simple"
PYPI_MIRROR_NETEASE: Literal["https://mirrors.163.com/pypi/simple"] = "https://mirrors.163.com/pypi/simple"
PYPI_MIRROR_SAU: Literal["https://pypi.sau.edu.cn/simple"] = "https://pypi.sau.edu.cn/simple"

# Poetry mirrors (uses same PyPI mirrors)
POETRY_REPO_TSINGHUA: Literal["https://pypi.tuna.tsinghua.edu.cn/simple"] = "https://pypi.tuna.tsinghua.edu.cn/simple"
POETRY_REPO_ALIYUN: Literal["https://mirrors.aliyun.com/pypi/simple"] = "https://mirrors.aliyun.com/pypi/simple"

# Default mirror selection
DEFAULT_GO_MIRROR: str = GO_PROXY_GOPROXY_CN
DEFAULT_PIP_MIRROR: str = PYPI_MIRROR_TSINGHUA


class MirrorConfig(TypedDict):
    """Mirror configuration for package managers."""
    name: str
    url: str
    environment_prefix: str
    environment_variables: dict[str, str]


# Predefined mirror configurations for different package managers
MIRROR_CONFIGS: dict[str, MirrorConfig] = {
    "npm": {
        "name": "NPM China Mirror (npmmirror)",
        "url": NPM_REGISTRY_NPMMIRROR,
        "environment_prefix": "NPM",
        "environment_variables": {
            "NPM_CONFIG_REGISTRY": NPM_REGISTRY_NPMMIRROR,
        },
    },
    "pnpm": {
        "name": "PNPM China Mirror (npmmirror)",
        "url": NPM_REGISTRY_NPMMIRROR,
        "environment_prefix": "PNPM",
        "environment_variables": {
            "PNPM_CONFIG_REGISTRY": NPM_REGISTRY_NPMMIRROR,
        },
    },
    "yarn": {
        "name": "Yarn China Mirror (npmmirror)",
        "url": NPM_REGISTRY_NPMMIRROR,
        "environment_prefix": "YARN",
        "environment_variables": {
            "YARN_NPM_MIRROR": NPM_REGISTRY_NPMMIRROR,
        },
    },
    "go": {
        "name": "Go China Mirror (goproxy.cn)",
        "url": GO_PROXY_GOPROXY_CN,
        "environment_prefix": "GOPROXY",
        "environment_variables": {
            "GOPROXY": f"{GO_PROXY_GOPROXY_CN},direct",
            "GOSUMDB": GO_SUMDB_GOLANG_GOOGLE_CN,
        },
    },
    "go_qiniu": {
        "name": "Go China Mirror (goproxy.io)",
        "url": GO_PROXY_GOPROXY_IO,
        "environment_prefix": "GOPROXY",
        "environment_variables": {
            "GOPROXY": f"{GO_PROXY_GOPROXY_IO},direct",
            "GOSUMDB": GO_SUMDB_GOLANG_GOOGLE_CN,
        },
    },
    "go_vip": {
        "name": "Go China Mirror (goproxy.vip.cn)",
        "url": GO_PROXY_GOVIP_CN,
        "environment_prefix": "GOPROXY",
        "environment_variables": {
            "GOPROXY": f"{GO_PROXY_GOVIP_CN},direct",
            "GOSUMDB": GO_SUMDB_GOLANG_GOOGLE_CN,
        },
    },
    "pip": {
        "name": "Pip China Mirror (Tsinghua)",
        "url": PYPI_MIRROR_TSINGHUA,
        "environment_prefix": "PIP",
        "environment_variables": {
            "PIP_INDEX_URL": f"{PYPI_MIRROR_TSINGHUA}/simple",
            "PIP_TRUSTED_HOST": "pypi.tuna.tsinghua.edu.cn",
        },
    },
    "pip_aliyun": {
        "name": "Pip China Mirror (Aliyun)",
        "url": PYPI_MIRROR_ALIYUN,
        "environment_prefix": "PIP",
        "environment_variables": {
            "PIP_INDEX_URL": f"{PYPI_MIRROR_ALIYUN}/simple",
            "PIP_TRUSTED_HOST": "mirrors.aliyun.com",
        },
    },
    "pip_douban": {
        "name": "Pip China Mirror (Douban)",
        "url": PYPI_MIRROR_DOUBAN,
        "environment_prefix": "PIP",
        "environment_variables": {
            "PIP_INDEX_URL": f"{PYPI_MIRROR_DOUBAN}/simple",
            "PIP_TRUSTED_HOST": "pypi.doubanio.com",
        },
    },
    "pip_huawei": {
        "name": "Pip China Mirror (Huawei)",
        "url": PYPI_MIRROR_HUAWEI,
        "environment_prefix": "PIP",
        "environment_variables": {
            "PIP_INDEX_URL": f"{PYPI_MIRROR_HUAWEI}/simple",
            "PIP_TRUSTED_HOST": "repo.huaweicloud.com",
        },
    },
    "python": {
        "name": "PyPI China Mirror (Tsinghua)",
        "url": PYPI_MIRROR_TSINGHUA,
        "environment_prefix": "PIP",
        "environment_variables": {
            "PIP_INDEX_URL": f"{PYPI_MIRROR_TSINGHUA}/simple",
            "PIP_TRUSTED_HOST": "pypi.tuna.tsinghua.edu.cn",
        },
    },
    "poetry": {
        "name": "Poetry China Mirror (Tsinghua)",
        "url": PYPI_MIRROR_TSINGHUA,
        "environment_prefix": "POETRY",
        "environment_variables": {
            "POETRY_REPOSITORIES_PYPI_URL": f"{POETRY_REPO_TSINGHUA}/simple",
        },
    },
}


def get_mirror_config(package_manager: str) -> MirrorConfig | None:
    """Get mirror configuration for a specific package manager.
    
    Args:
        package_manager: Name of the package manager (e.g., "npm", "go", "pip")
        
    Returns:
        MirrorConfig if found, None otherwise.
    """
    normalized_name = package_manager.lower().strip()
    return MIRROR_CONFIGS.get(normalized_name)


def apply_mirror_environment(
    package_manager: str, 
    environment: dict[str, str]
) -> dict[str, str]:
    """Apply mirror environment variables to the environment dict.
    
    Args:
        package_manager: Name of the package manager
        environment: Existing environment variables
        
    Returns:
        Updated environment with mirror variables added.
    """
    mirror_config = get_mirror_config(package_manager)
    if mirror_config is None:
        return environment
    
    mirror_vars = mirror_config.get("environment_variables", {})
    updated_env = environment.copy()
    updated_env.update(mirror_vars)
    
    return updated_env


def reset_mirror_environment(
    package_manager: str, 
    environment: dict[str, str]
) -> dict[str, str]:
    """Remove mirror environment variables from the environment dict.
    
    Args:
        package_manager: Name of the package manager
        environment: Existing environment variables
        
    Returns:
        Environment with mirror variables removed.
    """
    mirror_config = get_mirror_config(package_manager)
    if mirror_config is None:
        return environment
    
    mirror_vars = mirror_config.get("environment_variables", {})
    updated_env = environment.copy()
    
    for key in mirror_vars:
        updated_env.pop(key, None)
    
    return updated_env


def get_all_mirror_names() -> list[str]:
    """Get list of all available mirror names.
    
    Returns:
        List of package manager names with mirror support.
    """
    return list(MIRROR_CONFIGS.keys())


def validate_mirror_config(mirror_config: MirrorConfig) -> bool:
    """Validate a mirror configuration.
    
    Args:
        mirror_config: Mirror configuration to validate
        
    Returns:
        True if valid, False otherwise.
    """
    required_fields = ["name", "url", "environment_prefix", "environment_variables"]
    
    for field in required_fields:
        if field not in mirror_config or not mirror_config[field]:
            return False
    
    # Validate URL format
    url = mirror_config["url"]
    if not (url.startswith("http://") or url.startswith("https://")):
        return False
    
    return True


# Go mirrors in failover order (goproxy.io → goproxy.cn → goproxy.vip.cn)
GO_MIRROR_FALLBACK_ORDER = ["go_qiniu", "go", "go_vip"]


def get_go_mirror_with_fallback(failover: bool = True) -> list[str]:
    """Get Go mirror list for failover.

    Args:
        failover: If True, return all mirrors in fallback order.
                 If False, return only the default mirror.

    Returns:
        List of mirror keys to try.
    """
    if failover:
        return GO_MIRROR_FALLBACK_ORDER
    return ["go"]
