# !/usr/bin/env python
# -*-coding:utf-8 -*-

"""
# Time       ：2025/12/22 21:53
# Author     ：Maxwell
# Description：
"""
from typing import Optional
from fastapi import FastAPI
import redis.asyncio as redis
from fastapi_cache import FastAPICache
from fastapi_cache.backends.redis import RedisBackend
from loguru import logger
from infoman.config import settings


class RedisManager:
    """Redis 管理器"""

    def __init__(self):
        self.client: Optional[redis.Redis] = None

    async def startup(self, app: FastAPI):
        if not settings.redis_configured:
            logger.info("⏭️ Redis 未配置，跳过")
            return

        logger.info("📦 初始化 Redis...")

        try:
            # 创建连接池
            pool = redis.ConnectionPool(
                host=settings.REDIS_HOST,
                port=settings.REDIS_PORT,
                db=settings.REDIS_DB,
                password=settings.REDIS_PASSWORD,
                encoding="utf-8",
                decode_responses=False,
                max_connections=settings.REDIS_MAX_CONNECTIONS,
                socket_timeout=settings.REDIS_SOCKET_TIMEOUT,
                socket_connect_timeout=settings.REDIS_SOCKET_CONNECT_TIMEOUT,
                health_check_interval=settings.REDIS_HEALTH_CHECK_INTERVAL,
            )

            # 创建客户端
            self.client = redis.Redis(connection_pool=pool)
            app.state.redis_client = self.client

            # 测试连接
            await self.client.ping()

            # 初始化缓存
            FastAPICache.init(
                RedisBackend(self.client),
                prefix=f"{settings.REDIS_CACHE_PREFIX}:v{settings.APP_VERSION}:",
            )

            logger.success(f"✅ Redis 连接成功: {settings.REDIS_HOST}:{settings.REDIS_PORT}")

        except Exception as e:
            logger.error(f"❌ Redis 连接失败: {e}")
            self.client = None

    async def shutdown(self):
        """关闭 Redis"""
        if self.client:
            try:
                await self.client.close()
                await self.client.connection_pool.disconnect()
                logger.success("✅ Redis 已关闭")
            except Exception as e:
                logger.error(f"❌ Redis 关闭失败: {e}")

    async def health_check(self) -> dict:
        """健康检查"""
        if not self.client:
            return {"status": "not_configured"}

        try:
            await self.client.ping()
            return {"status": "healthy"}
        except Exception as e:
            return {"status": "unhealthy", "error": str(e)}
