"""
Redis连接管理
"""
from typing import Optional
from redis import asyncio as aioredis
from app.core.config import settings
from app.core.logger import logger

# 全局Redis连接实例
redis_client: Optional[aioredis.Redis] = None


async def init_redis() -> aioredis.Redis:
    """初始化Redis连接"""
    global redis_client

    try:
        redis_client = await aioredis.from_url(
            settings.REDIS_URL, encoding="utf-8", decode_responses=True
        )
        # 测试连接
        await redis_client.ping()
        logger.info("Redis连接成功", url=settings.REDIS_URL)
        return redis_client
    except Exception as e:
        logger.error("Redis连接失败", error=str(e), url=settings.REDIS_URL)
        raise


async def close_redis():
    """关闭Redis连接"""
    global redis_client

    if redis_client:
        await redis_client.close()
        logger.info("Redis连接已关闭")
        redis_client = None


def get_redis_client() -> aioredis.Redis:
    """获取Redis客户端实例"""
    if not redis_client:
        raise RuntimeError("Redis client not initialized")
    return redis_client
