"""
平台健康检查API - 验证各AI平台适配器状态

端点: GET /api/platforms/health
返回: 各平台适配器配置状态和健康信息
"""

import logging
from typing import Annotated

from fastapi import APIRouter, Depends

from app.config import settings

logger = logging.getLogger(__name__)

router = APIRouter(prefix="/api/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


def check_kimi_health() -> PlatformHealthStatus:
    """检查Kimi平台健康状态"""
    try:
        from app.workers.platforms.kimi import KimiAdapter

        adapter = KimiAdapter()
        api_key_set = bool(adapter.api_key and adapter.api_key.strip())
        configured = adapter.is_configured

        return PlatformHealthStatus(
            name="kimi",
            url=adapter.platform_url,
            configured=configured,
            api_key_set=api_key_set,
            status="configured" if configured else "not_configured",
            message="API Key已配置" if configured else "API Key未配置",
        )
    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:
        from app.workers.platforms.wenxin import WenxinAdapter

        adapter = WenxinAdapter()
        api_key_set = bool(adapter.api_key and adapter.api_key.strip())
        secret_key_set = bool(adapter.secret_key and adapter.secret_key.strip())
        configured = adapter.is_configured

        return PlatformHealthStatus(
            name="wenxin",
            url=adapter.platform_url,
            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:
        from app.workers.platforms.doubao import DoubaoAdapter

        adapter = DoubaoAdapter()
        api_key_set = bool(adapter.api_key and adapter.api_key.strip())
        configured = adapter.is_configured

        return PlatformHealthStatus(
            name="doubao",
            url=adapter.platform_url,
            configured=configured,
            api_key_set=api_key_set,
            status="configured" if configured else "not_configured",
            message="API Key已配置" if configured else "API Key未配置",
        )
    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():
    """
    获取所有AI平台适配器的健康状态

    返回每个平台的:
    - name: 平台名称
    - configured: 是否已配置
    - url: 平台URL
    - api_key_set: API Key是否已设置
    - status: 健康状态 (configured / not_configured / error)
    - message: 状态消息
    """
    health_info = check_all_platforms()
    return health_info


@router.get("/health/{platform_name}")
async def get_platform_health_by_name(platform_name: str):
    """
    获取指定平台适配器的健康状态

    Args:
        platform_name: 平台名称 (kimi / wenxin / doubao)
    """
    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
