import logging
import redis
from app.config import REDIS_HOST, REDIS_PORT, REDIS_DB, REDIS_PASSWORD

logger = logging.getLogger(__name__)

redis_client = None


def init_redis():
    """初始化 Redis 客户端，失败时返回 None"""
    global redis_client
    try:
        redis_client = redis.Redis(
            host=REDIS_HOST, port=REDIS_PORT, db=REDIS_DB,
            password=REDIS_PASSWORD or None,
            decode_responses=True,
            socket_connect_timeout=5,
        )
        redis_client.ping()
        logger.info("Redis 连接初始化成功")
        return redis_client
    except Exception as e:
        logger.warning(f"Redis 初始化失败: {e}")
        redis_client = None
        return None


def get_redis():
    """获取 Redis 客户端实例"""
    return redis_client
