"""Caching for enhancement service."""

import hashlib
import json
import logging
from typing import Any, Dict, Optional

from .models import EnhancementResult

logger = logging.getLogger(__name__)


class EnhancementCache:
    """Cache for enhancement results."""

    def __init__(self, enable_caching: bool = True, cache_ttl: int = 86400):
        """Initialize enhancement cache.

        Args:
            enable_caching: Whether to enable caching
            cache_ttl: Cache TTL in seconds

        """
        self.enable_caching = enable_caching
        self.cache_ttl = cache_ttl
        self.cache: Dict[str, EnhancementResult] = {}

    def get(self, cache_key: str) -> Optional[EnhancementResult]:
        """Get cached enhancement result.

        Args:
            cache_key: Cache key

        Returns:
            Cached result or None

        """
        if not self.enable_caching:
            return None

        if cache_key in self.cache:
            logger.info("Using cached enhancement result")
            return self.cache[cache_key]

        return None

    def set(self, cache_key: str, result: EnhancementResult) -> None:
        """Set cached enhancement result.

        Args:
            cache_key: Cache key
            result: Enhancement result

        """
        if not self.enable_caching:
            return

        self.cache[cache_key] = result

    def clear(self) -> None:
        """Clear the enhancement cache."""
        self.cache.clear()
        logger.info("Enhancement cache cleared")

    def get_stats(self) -> Dict[str, Any]:
        """Get cache statistics."""
        return {
            "cache_size": len(self.cache),
            "cache_enabled": self.enable_caching,
            "cache_ttl": self.cache_ttl
        }


def generate_cache_key(transcript: str, config: Dict[str, Any], kwargs: Dict[str, Any]) -> str:
    """Generate cache key for transcript and parameters.

    Args:
        transcript: Transcript text
        config: Enhancement configuration
        kwargs: Enhancement parameters

    Returns:
        Cache key string

    """
    # Create deterministic key from transcript and relevant parameters
    key_data = {
        "transcript": transcript,
        "model": config.get("model", "deepseek-chat"),
        "temperature": kwargs.get("temperature", config.get("temperature", 0.0)),
        "max_tokens": kwargs.get("max_tokens", config.get("max_tokens", 4096)),
        "preserve_timestamps": kwargs.get("preserve_timestamps", config.get("preserve_timestamps", True)),
        "preserve_speaker_markers": kwargs.get("preserve_speaker_markers", config.get("preserve_speaker_markers", True))
    }
    
    key_string = json.dumps(key_data, sort_keys=True)
    return hashlib.sha256(key_string.encode()).hexdigest()
