"""
Redis异步连接管理
"""
import os
import logging
from typing import Optional

# 导入配置
from app.core.config import config_handler

logger = logging.getLogger(__name__)

_redis_client = None


def get_redis_config() -> dict:
    """获取Redis配置"""
    config = {
        'host': config_handler.get("admin_app", "REDIS_HOST", "localhost"),
        'port': config_handler.get_int("admin_app", "REDIS_PORT", 6379),
        'db': config_handler.get_int("admin_app", "REDIS_DB", 0),
        'password': config_handler.get("admin_app", "REDIS_PASSWORD", None),
        'decode_responses': True
    }
    return config


def get_redis_connection():
    """获取Redis连接"""
    global _redis_client
    if _redis_client is None:
        try:
            import redis
            config = get_redis_config()
            _redis_client = redis.Redis(**config)
            _redis_client.ping()
            logger.info("Redis连接成功")
        except Exception as e:
            logger.warning(f"Redis连接失败: {e}")
            _redis_client = None
    return _redis_client


async def init_redis():
    """初始化Redis连接"""
    try:
        get_redis_connection()
        logger.info("Redis初始化成功")
    except Exception as e:
        logger.warning(f"Redis初始化失败: {e}")


async def close_redis():
    """关闭Redis连接"""
    global _redis_client
    if _redis_client:
        try:
            _redis_client.close()
            logger.info("Redis连接已关闭")
        except Exception as e:
            logger.error(f"关闭Redis连接失败: {e}")
        finally:
            _redis_client = None
