import logging
import os
from typing import Annotated

from fastapi import APIRouter, Depends

from app.config import settings

logger = logging.getLogger(__name__)

router = APIRouter(prefix="/platforms", tags=["platforms"])


class PlatformHealthStatus:

    def __init__(
        self,
        name: str,
        configured: bool,
        url: str = "",
        api_key_set: bool = False,
        status: str = "unknown",
        message: str = "",
    ):
        self.name = name
        self.configured = configured
        self.url = url
        self.api_key_set = api_key_set
        self.status = status
        self.message = message


_PLATFORM_URLS = {
    "kimi": "https://kimi.moonshot.cn",
    "wenxin": "https://yiyan.baidu.com",
    "doubao": "https://www.doubao.com/",
}


def _check_api_key_health(
    platform_name: str,
    env_key_name: str,
    url: str,
) -> PlatformHealthStatus:
    api_key = os.getenv(env_key_name, "")
    api_key_set = bool(api_key and api_key.strip())
    configured = api_key_set

    return PlatformHealthStatus(
        name=platform_name,
        url=url,
        configured=configured,
        api_key_set=api_key_set,
        status="configured" if configured else "not_configured",
        message="API Key已配置" if configured else "API Key未配置",
    )


def check_kimi_health() -> PlatformHealthStatus:
    try:
        return _check_api_key_health(
            platform_name="kimi",
            env_key_name="MOONSHOT_API_KEY",
            url=_PLATFORM_URLS["kimi"],
        )
    except Exception as e:
        logger.error(f"Kimi健康检查失败: {e}")
        return PlatformHealthStatus(
            name="kimi",
            configured=False,
            status="error",
            message=str(e),
        )


def check_wenxin_health() -> PlatformHealthStatus:
    try:
        api_key = os.getenv("BAIDU_QIANFAN_API_KEY", "")
        secret_key = os.getenv("BAIDU_QIANFAN_SECRET_KEY", "")
        api_key_set = bool(api_key and api_key.strip())
        secret_key_set = bool(secret_key and secret_key.strip())
        configured = api_key_set and secret_key_set

        return PlatformHealthStatus(
            name="wenxin",
            url=_PLATFORM_URLS["wenxin"],
            configured=configured,
            api_key_set=api_key_set,
            status="configured" if configured else "not_configured",
            message="API Key和Secret Key已配置" if configured else "API Key或Secret Key未配置",
        )
    except Exception as e:
        logger.error(f"文心健康检查失败: {e}")
        return PlatformHealthStatus(
            name="wenxin",
            configured=False,
            status="error",
            message=str(e),
        )


def check_doubao_health() -> PlatformHealthStatus:
    try:
        return _check_api_key_health(
            platform_name="doubao",
            env_key_name="DOUBAO_API_KEY",
            url=_PLATFORM_URLS["doubao"],
        )
    except Exception as e:
        logger.error(f"豆包健康检查失败: {e}")
        return PlatformHealthStatus(
            name="doubao",
            configured=False,
            status="error",
            message=str(e),
        )


def check_all_platforms() -> dict:
    platforms = [
        check_kimi_health(),
        check_wenxin_health(),
        check_doubao_health(),
    ]

    return {
        "platforms": [vars(p) for p in platforms],
        "total": len(platforms),
        "configured_count": sum(1 for p in platforms if p.configured),
    }


@router.get("/health")
async def get_platform_health():
    health_info = check_all_platforms()
    return health_info


@router.get("/health/{platform_name}")
async def get_platform_health_by_name(platform_name: str):
    if platform_name == "kimi":
        result = vars(check_kimi_health())
    elif platform_name == "wenxin":
        result = vars(check_wenxin_health())
    elif platform_name == "doubao":
        result = vars(check_doubao_health())
    else:
        return {"error": f"未知平台: {platform_name}"}

    return result
