from __future__ import annotations

from typing import Any

from niannian.llm.providers.anthropic import AnthropicProvider
from niannian.llm.providers.base import LLMProvider
from niannian.llm.providers.openai_compat import OpenAICompatProvider

# 存储 / OAuth 等非 LLM 配置节，不参与 LLM 路由
_STORAGE_PROVIDERS = frozenset(
    {
        "quark",
        "baidu",
        "feimao",
        "onedrive",
        "google_drive",
    }
)

# 国内 OpenAI 兼容 API 默认 base_url（providers.local 可覆盖）
DEFAULT_LLM_BASE_URLS: dict[str, str] = {
    "openai_compat": "https://api.siliconflow.cn/v1",
    "siliconflow": "https://api.siliconflow.cn/v1",
    "deepseek": "https://api.deepseek.com/v1",
    "custom": "",
    "moonshot": "https://api.moonshot.cn/v1",
    "dashscope": "https://dashscope.aliyuncs.com/compatible-mode/v1",
    "zhipu": "https://open.bigmodel.cn/api/paas/v4",
    "minimax": "https://api.minimax.chat/v1",
    "baichuan": "https://api.baichuan-ai.com/v1",
    "volcengine": "https://ark.cn-beijing.volces.com/api/v3",
    "qianfan": "https://qianfan.baidubce.com/v2",
    "spark": "https://maas-api.cn-huabei-1.xf-yun.com/v2",
}


def is_storage_provider(name: str) -> bool:
    return name in _STORAGE_PROVIDERS


def is_llm_provider_name(name: str, providers_cfg: dict[str, Any] | None = None) -> bool:
    if is_storage_provider(name):
        return False
    if name == "anthropic":
        return True
    if name in DEFAULT_LLM_BASE_URLS:
        return True
    cfg = (providers_cfg or {}).get(name)
    if isinstance(cfg, dict) and (cfg.get("api_key") or cfg.get("base_url")):
        return True
    return False


def provider_base_url(name: str, providers_cfg: dict[str, Any] | None = None) -> str | None:
    cfg = (providers_cfg or {}).get(name)
    if isinstance(cfg, dict):
        url = cfg.get("base_url")
        if url:
            return str(url).rstrip("/")
    return DEFAULT_LLM_BASE_URLS.get(name)


def normalize_llm_provider_config(name: str, cfg: dict[str, Any]) -> dict[str, Any]:
    out = dict(cfg)
    if not out.get("base_url"):
        default = DEFAULT_LLM_BASE_URLS.get(name)
        if default:
            out["base_url"] = default
    return out


def create_llm_provider(name: str, cfg: dict[str, Any]) -> LLMProvider | None:
    if is_storage_provider(name):
        return None
    if name == "anthropic":
        return AnthropicProvider(cfg)
    if is_llm_provider_name(name, {name: cfg}):
        return OpenAICompatProvider(normalize_llm_provider_config(name, cfg))
    return None
