"""
Exception handling for PowerBI MCP Server

Centralized error handling logic for HTTP errors and PowerBI-specific exceptions.
"""

import logging
import httpx

logger = logging.getLogger(__name__)


class PowerBIError(Exception):
    """Base exception for PowerBI operations"""
    pass


class AuthenticationError(PowerBIError):
    """Authentication failures"""
    pass


class APIError(PowerBIError):
    """API request failures"""
    pass


def handle_http_error(error: httpx.HTTPStatusError, context: str = "API request") -> PowerBIError:
    """
    Convert httpx.HTTPStatusError to PowerBIError with actionable messages

    Consolidates error handling from client.py and auth.py to provide
    consistent, user-friendly error messages.

    Args:
        error: The HTTP status error from httpx
        context: Context of the error ("API request", "authentication", etc.)

    Returns:
        PowerBIError subclass with detailed error message
    """
    # Extract error detail
    error_detail = ""
    try:
        error_detail = error.response.json()
    except Exception:
        error_detail = error.response.text

    status_code = error.response.status_code

    # Map status codes to specific errors
    if status_code == 401:
        logger.error("Authentication failed (401)")
        if context == "authentication":
            return AuthenticationError(
                f"PowerBI authentication failed with status {status_code}. "
                "Please verify your POWERBI_TENANT_ID, POWERBI_CLIENT_ID, and "
                f"POWERBI_CLIENT_SECRET are correct. Error details: {error_detail}"
            )
        else:
            return AuthenticationError(
                "Authentication failed (401). Your access token may have expired or "
                "your service principal may not have the required permissions. "
                "Ensure the service principal is enabled in PowerBI admin settings."
            )

    elif status_code == 403:
        logger.error("Access forbidden (403)")
        return APIError(
            "Access forbidden (403). Your service principal does not have "
            "permission to access this resource. Check PowerBI admin portal "
            "settings and ensure proper workspace access is granted."
        )

    elif status_code == 404:
        endpoint = error.request.url.path if hasattr(error.request, 'url') else "unknown"
        logger.error(f"Resource not found (404) at endpoint: {endpoint}")
        return APIError(
            f"Resource not found (404) at endpoint: {endpoint}. "
            "Please verify the workspace ID, dataset ID, or other identifiers are correct."
        )

    elif status_code == 429:
        retry_after = error.response.headers.get("Retry-After", "60")
        logger.warning(f"Rate limit exceeded (429). Retry after {retry_after}s")
        return APIError(
            f"Rate limit exceeded (429). Too many requests. "
            f"Please wait {retry_after} seconds before retrying."
        )

    else:
        logger.error(f"{context} failed with status {status_code}")
        return APIError(
            f"PowerBI {context} failed with status {status_code}. "
            f"Error details: {error_detail}"
        )
