"""Middleware for handling Google API errors gracefully."""

from __future__ import annotations

import logging

from fastmcp.server.middleware import Middleware
from fastmcp.exceptions import ToolError

logger = logging.getLogger("google-workspace-mcp")


class GoogleApiErrorHandler(Middleware):
    """Convert Google API HTTP errors into user-friendly ToolError messages."""

    async def on_call_tool(self, context, call_next):
        try:
            return await call_next(context)
        except ToolError:
            raise  # Pass through FastMCP errors
        except Exception as e:
            error_str = str(e)
            # Handle google-api-python-client HttpError
            if "HttpError" in type(e).__name__ or "HttpError" in error_str:
                if "429" in error_str or "rateLimitExceeded" in error_str:
                    raise ToolError(
                        "Google API rate limit exceeded. Please wait a moment and try again."
                    )
                if "403" in error_str or "forbidden" in error_str.lower():
                    raise ToolError(
                        "Permission denied. The account may not have access to this resource, "
                        "or the required API is not enabled in Google Cloud Console."
                    )
                if "404" in error_str or "notFound" in error_str:
                    raise ToolError(
                        "Resource not found. Check the ID (message, file, spreadsheet, event) is correct."
                    )
                if "401" in error_str or "invalid_grant" in error_str:
                    raise ToolError(
                        "Authentication expired. Re-authenticate this profile with: gw-mcp-auth --profile <name> --force"
                    )
                raise ToolError(f"Google API error: {error_str}")

            # Handle credentials/config errors
            if "not authenticated" in error_str or "Config not found" in error_str:
                raise ToolError(error_str)

            logger.exception("Unexpected error in tool call")
            raise ToolError(f"Unexpected error: {error_str}")
