import redis.asyncio as redis

from .config import settings
from .logging import get_logger

logger = get_logger(__name__)

class RedisConnection:
    pool: redis.ConnectionPool = None
    client: redis.Redis = None


redis_conn = RedisConnection()


async def connect_to_redis():
    logger.info("Connecting to Redis...")
    redis_conn.pool = redis.ConnectionPool.from_url(
        settings.redis_url,
        encoding="utf-8",
        decode_responses=True,
        max_connections=20,
    )
    redis_conn.client = redis.Redis(connection_pool=redis_conn.pool)

    # Test connection
    try:
        await redis_conn.client.ping()
        logger.info("Successfully connected to Redis")
    except Exception as e:
        logger.error(f"Failed to connect to Redis: {e}")
        raise


async def close_redis_connection():
    logger.info("Closing Redis connection...")
    if redis_conn.client:
        await redis_conn.client.close()
    if redis_conn.pool:
        await redis_conn.pool.disconnect()


async def get_redis() -> redis.Redis:
    return redis_conn.client


def get_redis_client() -> redis.Redis:
    """Get the Redis client synchronously (for middleware setup)."""
    return redis_conn.client
