#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project ：django_base_ai
@File    ：__init__.py
@Desc    ：AI 调用辅助工具包，封装主流厂商 API（OpenAI 兼容、腾讯云等），支持自定义供应商
"""

import logging

from django_base_ai.utils.ai.base import (

    BaseAIClient,
    ChatMessage,
    ChatSession,
    CompletionResult,
    CustomProviderConfig,
    ModelItem,
)
from django_base_ai.utils.ai.deepseek import DeepSeekClient
from django_base_ai.utils.ai.openai_compat import DEFAULT_BASE_URLS, OpenAICompatClient
from django_base_ai.utils.ai.settings_conf import get_ai_config
from django_base_ai.utils.ai.tencent import TencentCloudAIClient

logger = logging.getLogger(__name__)


def client_from_custom_config(config: CustomProviderConfig) -> BaseAIClient:
    """
    从「自定义 API 配置」创建客户端，与前端编辑供应商表单对应。
    :param config: 名称、API 格式、API Key、前置 URL、模型列表等
    """
    fmt = (config.api_format or "OpenAI").strip().lower()
    if fmt == "openai":
        default_model = config.default_model
        if not default_model and config.models:
            default_model = config.models[0].model_id
        return OpenAICompatClient(
            api_key=config.api_key,
            base_url=config.base_url.rstrip("/"),
            default_model=default_model or "gpt-3.5-turbo",
        )
    raise ValueError(f"不支持的 API 格式: {config.api_format}")


def get_client(
    provider: str,
    api_key: str,
    base_url: str | None = None,
    default_model: str | None = None,
) -> BaseAIClient:
    """
    按供应商名获取 AI 客户端。
    :param provider: openai / deepseek / openai_custom / tencent
    :param api_key: API Key
    :param base_url: 可选，自定义端点（openai_custom 或自建时必填或在此传入）
    :param default_model: 可选默认模型
    """
    if provider == "tencent":
        return TencentCloudAIClient(
            api_key=api_key,
            default_model=default_model or "hunyuan-lite",
        )
    if provider == "deepseek":
        return DeepSeekClient(
            api_key=api_key,
            default_model=default_model or "deepseek-chat",
        )
    return OpenAICompatClient(
        api_key=api_key,
        base_url=base_url,
        default_model=default_model or "gpt-3.5-turbo",
        provider=provider if provider in DEFAULT_BASE_URLS else "openai_custom",
    )


def get_client_from_settings(provider: str) -> BaseAIClient:
    """
    从 conf 配置（经 Django settings）读取 api_key 等并创建客户端。
    需在 conf/env.py、conf/pro.py 等中设置对应变量，例如：
    - DeepSeek: AI_DEEPSEEK_API_KEY，可选 AI_DEEPSEEK_DEFAULT_MODEL
    - 腾讯云: AI_TENCENT_API_KEY，可选 AI_TENCENT_DEFAULT_MODEL
    - OpenAI: AI_OPENAI_API_KEY，可选 AI_OPENAI_BASE_URL、AI_OPENAI_DEFAULT_MODEL
    - 自定义: AI_OPENAI_CUSTOM_API_KEY、AI_OPENAI_CUSTOM_BASE_URL（必填），可选 AI_OPENAI_CUSTOM_DEFAULT_MODEL
    """
    cfg = get_ai_config(provider)
    if not cfg["api_key"]:
        logger.warning("未配置 AI_%s_API_KEY，请在 conf 中设置", provider.upper())
        raise ValueError(f"未配置 AI_{provider.upper()}_API_KEY，请在 conf 中设置")
    return get_client(
        provider=provider,
        api_key=cfg["api_key"],
        base_url=cfg.get("base_url"),
        default_model=cfg.get("default_model"),
    )


def test_api_key(config: CustomProviderConfig | BaseAIClient) -> tuple[bool, str]:
    """
    测试 API Key / 连接是否有效，供前端「测试」按钮调用。
    :param config: 自定义配置或已建客户端
    """
    if isinstance(config, BaseAIClient):
        return config.test_connection()
    client = client_from_custom_config(config)
    return client.test_connection()


__all__ = [
    "BaseAIClient",
    "ChatMessage",
    "ChatSession",
    "CompletionResult",
    "CustomProviderConfig",
    "DeepSeekClient",
    "ModelItem",
    "OpenAICompatClient",
    "TencentCloudAIClient",
    "client_from_custom_config",
    "get_client",
    "get_client_from_settings",
    "test_api_key",
    "DEFAULT_BASE_URLS",
]
