"""Caching functionality for Azure Key Vault secrets."""

import time
from typing import Optional, Dict, Any
from .exceptions import CacheError


class SecretCache:
    """A simple in-memory cache for storing Azure Key Vault secrets.
    
    This cache stores secrets with an optional TTL (time-to-live) to reduce
    repeated calls to Azure Key Vault.
    """

    def __init__(self, ttl_seconds: int = 300):
        """Initialize the secret cache.
        
        Args:
            ttl_seconds: Time-to-live for cached secrets in seconds. Defaults to 300 (5 minutes).
        """
        self._cache: Dict[str, Dict[str, Any]] = {}
        self.ttl_seconds = ttl_seconds

    def get(self, key: str) -> Optional[str]:
        """Retrieve a secret from cache if it exists and hasn't expired.
        
        Args:
            key: The cache key (typically the secret name).
            
        Returns:
            The cached secret value, or None if not found or expired.
        """
        if key not in self._cache:
            return None

        entry = self._cache[key]
        if time.time() > entry["expires_at"]:
            del self._cache[key]
            return None

        return entry["value"]

    def set(self, key: str, value: str) -> None:
        """Store a secret in cache with TTL.
        
        Args:
            key: The cache key (typically the secret name).
            value: The secret value to cache.
            
        Raises:
            CacheError: If an error occurs while caching.
        """
        try:
            self._cache[key] = {
                "value": value,
                "expires_at": time.time() + self.ttl_seconds,
            }
        except Exception as e:
            raise CacheError(f"Failed to cache secret '{key}': {str(e)}")

    def clear(self) -> None:
        """Clear all cached secrets."""
        self._cache.clear()

    def remove(self, key: str) -> None:
        """Remove a specific secret from cache.
        
        Args:
            key: The cache key to remove.
        """
        if key in self._cache:
            del self._cache[key]

    def is_expired(self, key: str) -> bool:
        """Check if a cached secret has expired.
        
        Args:
            key: The cache key to check.
            
        Returns:
            True if the secret is expired or not in cache, False otherwise.
        """
        if key not in self._cache:
            return True
        return time.time() > self._cache[key]["expires_at"]
