# vendor.py
from __future__ import annotations

DEFAULT = "laybot"

def _bearer(k: str) -> dict:
    return {"Authorization": f"Bearer {k}"} if k else {}

_VENDOR_TABLE: dict[str, dict] = {
    "laybot": {
        "base": "https://api.laybot.cn",
        "ep": {"chat": "/v1/chat", "embed": "/v1/chat", "doc": "/v1/doc"},
        "hdr": lambda k: {"X-API-Key": k} if k else {},
        "capabilities": {"cache": {"supported": True, "explicit": False, "implicit": True}},
    },
    "openai": {
        "base": "https://api.openai.com",
        "ep": {"chat": "/v1/chat/completions", "embed": "/v1/embeddings"},
        "hdr": _bearer,
        "capabilities": {"cache": {"supported": True, "explicit": False, "implicit": True}},
    },
    "deepseek": {
        "base": "https://api.deepseek.com",
        "ep": {"chat": "/chat/completions", "embed": "/v1/embeddings"},
        "hdr": _bearer,
        "capabilities": {"cache": {"supported": False, "explicit": False, "implicit": False}},
    },
    "grok": {
        "base": "https://api.groq.com",
        "ep": {"chat": "/openai/v1/chat/completions", "embed": "/openai/v1/embeddings"},
        "hdr": _bearer,
        "capabilities": {"cache": {"supported": False, "explicit": False, "implicit": False}},
    },
    "azure-openai": {
        "base": "https://{RESOURCE}.openai.azure.com",
        "ep": {
            "chat": "/openai/deployments/{DEPLOY}/chat/completions?api-version=2024-05-01-preview",
            "embed": "/openai/deployments/{DEPLOY}/embeddings?api-version=2024-05-01-preview",
        },
        "hdr": lambda k: {"api-key": k} if k else {},
        "capabilities": {"cache": {"supported": True, "explicit": False, "implicit": True}},
    },

    # Gemini Developer API（base 可替换为代理域名）
    "gemini": {
        "base": "https://generativelanguage.googleapis.com",
        "ep": {
            "chat": "/v1beta/models/{MODEL}:generateContent",
            "chat_stream": "/v1beta/models/{MODEL}:streamGenerateContent",
            "cache": "/v1beta/cachedContents",
        },
        # 关键：按你的约束，“默认使用 query ?key= 注入”，因此这里不要默认注入 header key
        "hdr": lambda k: {},
        "query_key_name": "key",
        "capabilities": {"cache": {"supported": True, "explicit": True, "implicit": True}},
    },
}

def info(vendor: str) -> dict:
    return _VENDOR_TABLE.get(vendor, _VENDOR_TABLE[DEFAULT])

def default_base(vendor: str) -> str:
    return info(vendor)["base"]

def default_ep(vendor: str, cap: str) -> str | None:
    return info(vendor)["ep"].get(cap)

def patch_hdr(vendor: str, api_key: str) -> dict:
    hdr_fn = info(vendor).get("hdr")
    return hdr_fn(api_key) if hdr_fn else {}

def query_key_name(vendor: str) -> str:
    return info(vendor).get("query_key_name", "key")

def capabilities(vendor: str) -> dict:
    return info(vendor).get("capabilities") or {}

# LayBot error meta table...
_LAYBOT_ERROR_TABLE: dict[int, dict] = {
    40001: {"http": 403, "err": "MODEL_NOT_ALLOWED"},
    40002: {"http": 400, "err": "PARAM_INVALID"},
    40003: {"http": 400, "err": "FUNCTION_UNSUPPORTED"},
    40004: {"http": 403, "err": "CAPABILITY_FORBIDDEN"},
    40005: {"http": 409, "err": "DUPLICATE_REQUEST"},
    40101: {"http": 401, "err": "API_KEY_INVALID"},
    40102: {"http": 401, "err": "IP_NOT_ALLOWED"},
    40200: {"http": 402, "err": "INSUFFICIENT_CREDIT"},
    41300: {"http": 413, "err": "PAYLOAD_TOO_LARGE"},
    41500: {"http": 415, "err": "UNSUPPORTED_MEDIA_TYPE"},
    42300: {"http": 423, "err": "JOB_NOT_FINISHED"},
    42900: {"http": 429, "err": "RATE_LIMITED"},
    50000: {"http": 500, "err": "INTERNAL_ERROR"},
    50001: {"http": 502, "err": "DEPENDENCY_ERROR"},
    50002: {"http": 504, "err": "TIMEOUT"},
    50300: {"http": 503, "err": "SERVICE_UNAVAILABLE"},
    50301: {"http": 503, "err": "MAINTENANCE_MODE"},
}

def laybot_error_meta(code: int) -> dict | None:
    return _LAYBOT_ERROR_TABLE.get(int(code))
