import os
from dataclasses import dataclass, field
from typing import List, Optional


@dataclass
class RateLimiterConfig:
    """Configuration for rate limiter."""

    backend: str = "redis"
    redis_url: str = "redis://localhost:6379"
    redis_cluster_mode: bool = False  # Enable Redis Cluster mode
    redis_key_prefix: str = "rateon"
    default_limits: List[str] = field(default_factory=list)
    trust_proxy_headers: bool = False
    fail_closed: bool = True  # Deny on backend failure
    enable_metrics: bool = True
    enable_logging: bool = True
    log_level: str = "INFO"

    @classmethod
    def from_env(cls) -> "RateLimiterConfig":
        """
        Create configuration from environment variables.

        Environment variables:
            RATE_LIMITER_BACKEND: Storage backend ("redis" or "memory")
            RATE_LIMITER_REDIS_URL: Redis connection URL. For cluster mode, a single node URL
                                   is sufficient (client auto-discovers other nodes). Multiple
                                   URLs (comma-separated) are optional for redundancy.
            RATE_LIMITER_REDIS_CLUSTER_MODE: Enable Redis Cluster mode (true/false)
            RATE_LIMITER_REDIS_KEY_PREFIX: Prefix for Redis keys
            RATE_LIMITER_TRUST_PROXY_HEADERS: Trust X-Forwarded-For headers (true/false)
            RATE_LIMITER_FAIL_CLOSED: Deny on backend failure (true/false)
            RATE_LIMITER_ENABLE_METRICS: Enable Prometheus metrics (true/false)
            RATE_LIMITER_ENABLE_LOGGING: Enable structured logging (true/false)
            RATE_LIMITER_LOG_LEVEL: Logging level (DEBUG, INFO, WARNING, ERROR)
        """
        backend = os.getenv("RATE_LIMITER_BACKEND", "redis")
        redis_url = os.getenv("RATE_LIMITER_REDIS_URL", "redis://localhost:6379")
        redis_cluster_mode = os.getenv("RATE_LIMITER_REDIS_CLUSTER_MODE", "false").lower() == "true"
        redis_key_prefix = os.getenv("RATE_LIMITER_REDIS_KEY_PREFIX", "rateon")
        trust_proxy_headers = os.getenv("RATE_LIMITER_TRUST_PROXY_HEADERS", "false").lower() == "true"
        fail_closed = os.getenv("RATE_LIMITER_FAIL_CLOSED", "true").lower() == "true"
        enable_metrics = os.getenv("RATE_LIMITER_ENABLE_METRICS", "true").lower() == "true"
        enable_logging = os.getenv("RATE_LIMITER_ENABLE_LOGGING", "true").lower() == "true"
        log_level = os.getenv("RATE_LIMITER_LOG_LEVEL", "INFO")

        return cls(
            backend=backend,
            redis_url=redis_url,
            redis_cluster_mode=redis_cluster_mode,
            redis_key_prefix=redis_key_prefix,
            trust_proxy_headers=trust_proxy_headers,
            fail_closed=fail_closed,
            enable_metrics=enable_metrics,
            enable_logging=enable_logging,
            log_level=log_level,
        )

    def __post_init__(self) -> None:
        """Validate configuration."""
        if self.backend not in ("redis", "memory"):
            raise ValueError(f"Invalid backend: {self.backend}. Must be 'redis' or 'memory'")
