#!/usr/bin/env python
"""
Redis 集群客户端，用于 django-redis
"""

from django_redis.client.default import DefaultClient
from redis.cluster import RedisCluster


class ClusterClient(DefaultClient):
    """
    自定义 Redis 集群客户端
    """

    def connect(self, index=0):
        """
        连接到 Redis 集群
        """
        # 从 OPTIONS 中获取集群配置
        options = self._options
        pool_kwargs = options.get("CONNECTION_POOL_CLASS_KWARGS", {})

        startup_nodes = pool_kwargs.get("startup_nodes", [])
        password = pool_kwargs.get("password", None)
        max_connections = pool_kwargs.get("max_connections", 100)
        # 注意：decode_responses 必须为 False，因为 django-redis 需要处理字节数据
        decode_responses = False
        skip_full_coverage_check = pool_kwargs.get("skip_full_coverage_check", True)

        if not startup_nodes:
            raise ValueError("startup_nodes 必须配置")

        # 创建 Redis 集群连接
        # redis.cluster.RedisCluster 支持相同的参数
        return RedisCluster(
            startup_nodes=startup_nodes,
            password=password,
            decode_responses=decode_responses,
            skip_full_coverage_check=skip_full_coverage_check,
            max_connections=max_connections,
        )
