"""
Storage backends for OCPP UDP client data
"""
import json
import logging
from abc import ABC, abstractmethod
from typing import Dict, Any, Optional, List
import asyncio
from .config import get_config

logger = logging.getLogger(__name__)
config = get_config()


class StorageBackend(ABC):
    """Abstract base class for storage backends"""
    
    @abstractmethod
    async def get(self, key: str) -> Optional[Any]:
        """Get a value by key"""
        pass
        
    @abstractmethod
    async def set(self, key: str, value: Any, ttl: Optional[int] = None) -> bool:
        """Set a value with optional TTL"""
        pass
        
    @abstractmethod
    async def delete(self, key: str) -> bool:
        """Delete a value by key"""
        pass
        
    @abstractmethod
    async def exists(self, key: str) -> bool:
        """Check if a key exists"""
        pass


class MemoryStorage(StorageBackend):
    """In-memory storage backend"""
    
    def __init__(self):
        self.data: Dict[str, Any] = {}
        self.ttl_data: Dict[str, float] = {}
        
    async def get(self, key: str) -> Optional[Any]:
        # Check TTL
        if key in self.ttl_data:
            import time
            if time.time() > self.ttl_data[key]:
                await self.delete(key)
                return None
                
        return self.data.get(key)
        
    async def set(self, key: str, value: Any, ttl: Optional[int] = None) -> bool:
        self.data[key] = value
        
        if ttl:
            import time
            self.ttl_data[key] = time.time() + ttl
        elif key in self.ttl_data:
            del self.ttl_data[key]
            
        return True
        
    async def delete(self, key: str) -> bool:
        if key in self.data:
            del self.data[key]
        if key in self.ttl_data:
            del self.ttl_data[key]
        return True
        
    async def exists(self, key: str) -> bool:
        value = await self.get(key)
        return value is not None


class RedisStorage(StorageBackend):
    """Redis storage backend (placeholder - requires redis-py)"""
    
    def __init__(self, host: str = None, port: int = None, db: int = None):
        self.host = host or config.redis_host
        self.port = port or config.redis_port
        self.db = db or config.redis_db
        self.redis = None
        logger.warning("RedisStorage is a placeholder - install redis-py for actual Redis support")
        
    async def get(self, key: str) -> Optional[Any]:
        # Placeholder implementation
        logger.warning("Redis backend not implemented - falling back to memory storage")
        return None
        
    async def set(self, key: str, value: Any, ttl: Optional[int] = None) -> bool:
        # Placeholder implementation
        logger.warning("Redis backend not implemented - falling back to memory storage")
        return False
        
    async def delete(self, key: str) -> bool:
        # Placeholder implementation
        return False
        
    async def exists(self, key: str) -> bool:
        # Placeholder implementation
        return False


def get_storage_backend() -> StorageBackend:
    """Get the configured storage backend"""
    backend_type = config.storage_backend
    
    if backend_type == "redis":
        return RedisStorage()
    else:
        return MemoryStorage()
