"""DS-specific error classes. Mirrors BPA error patterns for consistency."""

from fastmcp.exceptions import ToolError


class DSClientError(Exception):
    """Base error for DS API calls."""

    def __init__(self, message: str, status_code: int | None = None):
        super().__init__(message)
        self.status_code = status_code


class DSConnectionError(DSClientError):
    """Cannot reach the DS instance."""


class DSTimeoutError(DSClientError):
    """DS request timed out."""


class DSAuthenticationError(DSClientError):
    """Not authenticated (401)."""


class DSPermissionError(DSClientError):
    """Not authorized (403). Admin access required."""


class DSNotFoundError(DSClientError):
    """Resource not found (404)."""


class DSServerError(DSClientError):
    """DS server error (5xx)."""


def translate_error(
    error: Exception,
    *,
    resource_type: str | None = None,
    resource_id: str | int | None = None,
) -> ToolError:
    """Translate DS errors to AI-friendly ToolError messages."""
    if resource_type and resource_id:
        resource_desc = f" {resource_type} '{resource_id}'"
    elif resource_type:
        resource_desc = f" {resource_type}"
    else:
        resource_desc = ""

    if isinstance(error, DSConnectionError):
        return ToolError(
            "Cannot reach DS instance. Check instance "
            "configuration and run ds_health to verify."
        )
    if isinstance(error, DSTimeoutError):
        msg = "DS request timed out"
        if resource_desc:
            msg += f" for{resource_desc}"
        return ToolError(f"{msg}. Try again.")
    if isinstance(error, DSAuthenticationError):
        return ToolError("Not authenticated. Run ds_auth_login first.")
    if isinstance(error, DSPermissionError):
        msg = "Admin access required"
        if resource_desc:
            msg += f" for{resource_desc}"
        return ToolError(f"{msg}. Ensure user has is_staff or is_superuser flag.")
    if isinstance(error, DSNotFoundError):
        msg = "Not found"
        if resource_desc:
            msg += f":{resource_desc}"
        return ToolError(f"{msg}. Verify the ID exists.")
    if isinstance(error, DSServerError):
        msg = "DS server error"
        if resource_desc:
            msg += f" for{resource_desc}"
        return ToolError(f"{msg}. Run ds_health to check system status.")
    msg = "DS error"
    if resource_desc:
        msg += f" ({resource_desc.strip()})"
    return ToolError(f"{msg}: {error}")
