"""
Rate Limiter Configuration for Agentes IA - ValorMas
Uses SlowAPI with Redis backend for distributed rate limiting
"""

import os
import logging
from pathlib import Path
from slowapi import Limiter
from slowapi.util import get_remote_address
import redis
from dotenv import load_dotenv

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# Load environment variables from .env in the same directory
env_path = Path(__file__).parent / '.env'
load_dotenv(dotenv_path=env_path)

# Redis configuration
REDIS_HOST = os.getenv('REDIS_HOST', '127.0.0.1')
REDIS_PORT = int(os.getenv('REDIS_PORT', 6380))
REDIS_PASSWORD = os.getenv('REDIS_PASSWORD', '')
REDIS_DB = int(os.getenv('REDIS_DB', 0))
REDIS_TIMEOUT = int(os.getenv('REDIS_TIMEOUT', 5))

# Rate limit configurations
RATE_LIMIT_DEFAULT = os.getenv('RATE_LIMIT_DEFAULT', '100/minute')
RATE_LIMIT_CHAT_IA = os.getenv('RATE_LIMIT_CHAT_IA', '50/minute')
RATE_LIMIT_HEAVY_MODELS = os.getenv('RATE_LIMIT_HEAVY_MODELS', '20/minute')
RATE_LIMIT_MODELS = os.getenv('RATE_LIMIT_MODELS', '30/minute')
RATE_LIMIT_DATABASE = os.getenv('RATE_LIMIT_DATABASE', '100/minute')
RATE_LIMIT_SENSITIVE = os.getenv('RATE_LIMIT_SENSITIVE', '10/minute')

def get_redis_client():
    """
    Attempts to connect to Redis server
    Returns Redis client if successful, None otherwise
    """
    try:
        client = redis.Redis(
            host=REDIS_HOST,
            port=REDIS_PORT,
            password=REDIS_PASSWORD,
            db=REDIS_DB,
            socket_timeout=REDIS_TIMEOUT,
            socket_connect_timeout=REDIS_TIMEOUT,
            decode_responses=True
        )
        # Test connection
        client.ping()
        logger.info(f"[OK] Connected to Redis at {REDIS_HOST}:{REDIS_PORT}")
        return client
    except redis.ConnectionError as e:
        logger.warning(f"[WARN] Redis connection failed: {e}")
        logger.warning("Falling back to in-memory rate limiting")
        return None
    except Exception as e:
        logger.error(f"[ERROR] Unexpected error connecting to Redis: {e}")
        return None

# Initialize Redis client
redis_client = get_redis_client()

# Configure storage URI based on Redis availability
if redis_client:
    storage_uri = f"redis://:{REDIS_PASSWORD}@{REDIS_HOST}:{REDIS_PORT}/{REDIS_DB}"
else:
    storage_uri = "memory://"

# Initialize limiter
limiter = Limiter(
    key_func=get_remote_address,
    storage_uri=storage_uri,
    default_limits=[RATE_LIMIT_DEFAULT],
    headers_enabled=True,
    swallow_errors=True,
    strategy="moving-window"
)

logger.info(f"Rate limiter initialized with storage: {storage_uri.split('@')[0] if '@' in storage_uri else storage_uri}")
