"""
Redis客户端
"""
import redis
from app.core.config import settings
import logging

logger = logging.getLogger(__name__)

_redis_client = None

def get_redis_client():
    """
    获取Redis客户端（单例模式）
    
    Returns:
        redis.Redis: Redis客户端实例，如果连接失败则返回None
    """
    global _redis_client
    
    if _redis_client is not None:
        try:
            # 测试连接
            _redis_client.ping()
            return _redis_client
        except:
            # 连接已断开，重新创建
            _redis_client = None
    
    try:
        redis_url = getattr(settings, 'REDIS_URL', None)
        if not redis_url:
            logger.warning("REDIS_URL未配置，无法使用Redis缓存")
            return None
        
        # 解析Redis URL: redis://host:port/db
        if redis_url.startswith('redis://'):
            redis_url = redis_url.replace('redis://', '')
        
        # 分离host:port和db
        parts = redis_url.split('/')
        host_port = parts[0]
        db = int(parts[1]) if len(parts) > 1 and parts[1].isdigit() else 0
        
        # 分离host和port
        if ':' in host_port:
            host, port = host_port.split(':')
            port = int(port)
        else:
            host = host_port
            port = 6379
        
        _redis_client = redis.Redis(
            host=host,
            port=port,
            db=db,
            decode_responses=True,  # 自动解码为字符串
            socket_connect_timeout=2,
            socket_timeout=2
        )
        
        # 测试连接
        _redis_client.ping()
        logger.info(f"Redis连接成功: {host}:{port}/{db}")
        return _redis_client
    except Exception as e:
        logger.warning(f"Redis连接失败: {str(e)}，将使用内存缓存")
        _redis_client = None
        return None
