"""Cache management endpoints."""

import logging
from fastapi import APIRouter, HTTPException
from fastapi.responses import JSONResponse

from src.services.cache_service import cache_service

logger = logging.getLogger(__name__)
router = APIRouter()


@router.get("/stats")
async def get_cache_stats():
    """Get cache statistics."""
    try:
        if cache_service:
            stats = cache_service.get_cache_stats()
            return JSONResponse(content=stats)
        else:
            return JSONResponse(content={"enabled": False})
    except Exception as e:
        logger.error(f"Error getting cache stats: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.delete("/")
async def clear_cache():
    """Clear all cached results."""
    try:
        if cache_service and hasattr(cache_service, 'invalidate_cache'):
            cleared_count = cache_service.invalidate_cache()
            return JSONResponse(content={
                "message": f"Cleared {cleared_count} cached entries",
                "cleared_count": cleared_count
            })
        else:
            return JSONResponse(content={"message": "Cache not enabled"})
    except Exception as e:
        logger.error(f"Error clearing cache: {e}")
        raise HTTPException(status_code=500, detail=str(e))
