"""
Redis connection and cache management.
"""
import json
import redis.asyncio as redis
from typing import Optional, Any
import structlog
from app.core.config import settings

logger = structlog.get_logger(__name__)

class RedisClient:
    """Redis client wrapper for caching and state management."""
    
    def __init__(self):
        self.client: Optional[redis.Redis] = None
        
    async def connect(self):
        """Create Redis connection pool."""
        if self.client:
            return
            
        try:
            self.client = await redis.from_url(
                settings.redis_url,
                encoding="utf-8",
                decode_responses=True
            )
            await self.client.ping()
            logger.info("redis_connected")
        except Exception as e:
            logger.error("redis_connection_failed", error=str(e))
            raise
            
    async def disconnect(self):
        """Close Redis connection."""
        if self.client:
            await self.client.close()
            logger.info("redis_disconnected")
            
    async def get(self, key: str) -> Optional[Any]:
        """Get value from Redis."""
        try:
            value = await self.client.get(key)
            if value:
                return json.loads(value)
            return None
        except Exception as e:
            logger.error("redis_get_failed", key=key, error=str(e))
            return None
            
    async def set(self, key: str, value: Any, ttl: int = 3600):
        """Set value in Redis with TTL (default 1 hour)."""
        try:
            await self.client.setex(
                key,
                ttl,
                json.dumps(value)
            )
        except Exception as e:
            logger.error("redis_set_failed", key=key, error=str(e))
            
    async def delete(self, key: str):
        """Delete key from Redis."""
        try:
            await self.client.delete(key)
        except Exception as e:
            logger.error("redis_delete_failed", key=key, error=str(e))

# Global Redis instance
redis_client = RedisClient()
