"""
Cache Analytics API Routes
===========================

Provides endpoints to monitor semantic cache performance:
- Cache statistics (hit rate, cost savings, performance)
- Clear user cache
- Reset statistics
"""

import logging

from fastapi import APIRouter

from common.cache import clear_user_cache, get_cache_stats, reset_cache_stats

logger = logging.getLogger(__name__)

router = APIRouter(prefix="/cache", tags=["Cache Analytics"])


@router.get("/stats")
async def get_cache_statistics():
    """
    Get semantic cache performance statistics.
    
    Returns:
        Cache stats including:
        - LLM cache hit/miss rates
        - Embedding cache hit/miss rates  
        - Cost savings (USD)
        - Performance metrics (time saved)
    
    Example Response:
    ```json
    {
        "total_queries": 150,
        "llm_cache": {
            "hits": 90,
            "misses": 60,
            "hit_rate_percent": 60.0,
            "cost_saved_usd": 0.09
        },
        "embedding_cache": {
            "hits": 120,
            "misses": 30,
            "hit_rate_percent": 80.0,
            "cost_saved_usd": 0.012
        },
        "performance": {
            "avg_saved_time_ms": 1850,
            "total_time_saved_seconds": 166.5
        },
        "total_cost_saved_usd": 0.102
    }
    ```
    """
    try:
        stats = await get_cache_stats()
        return {
            "status": "success",
            "data": stats,
        }
    except Exception as e:
        logger.error(f"Error getting cache stats: {e}", exc_info=True)
        return {
            "status": "error",
            "message": str(e),
        }


@router.delete("/user/{user_id}")
async def clear_cache_for_user(user_id: str):
    """
    Clear all cached responses for a specific user.
    
    Args:
        user_id: User ID to clear cache for
    
    Returns:
        Number of cache entries deleted
    
    Use cases:
    - User requests to clear their data
    - User reports incorrect cached responses
    - Manual cache invalidation for testing
    """
    try:
        deleted_count = await clear_user_cache(user_id)
        return {
            "status": "success",
            "message": f"Cleared {deleted_count} cache entries for user {user_id}",
            "deleted_count": deleted_count,
        }
    except Exception as e:
        logger.error(f"Error clearing user cache: {e}", exc_info=True)
        return {
            "status": "error",
            "message": str(e),
        }


@router.post("/stats/reset")
async def reset_statistics():
    """
    Reset cache statistics counters.
    
    This resets:
    - Hit/miss counters
    - Cost savings calculations
    - Performance metrics
    
    Note: This does NOT delete cached data, only resets the statistics.
    """
    try:
        reset_cache_stats()
        return {
            "status": "success",
            "message": "Cache statistics reset successfully",
        }
    except Exception as e:
        logger.error(f"Error resetting cache stats: {e}", exc_info=True)
        return {
            "status": "error",
            "message": str(e),
        }
