from __future__ import annotations

from fastmcp.exceptions import ToolError


class SmartLinkClientError(Exception):
    """Base error for all SmartLink client operations."""

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


class SmartLinkAuthError(SmartLinkClientError):
    """401 — token expired or invalid."""


class SmartLinkForbiddenError(SmartLinkClientError):
    """403 — insufficient permissions (requires bot or sysadmin role)."""


class SmartLinkNotFoundError(SmartLinkClientError):
    """404 — resource not found."""


class SmartLinkValidationError(SmartLinkClientError):
    """400 — malformed or invalid parameters."""


class SmartLinkServerError(SmartLinkClientError):
    """500+ — server-side error."""


def translate_error(
    error: Exception,
    *,
    resource_type: str | None = None,
    resource_id: str | None = None,
) -> ToolError:
    """Translate a SmartLink client error into an AI-friendly ToolError."""
    resource_desc = resource_type or "resource"
    if resource_id is not None:
        resource_desc = f"{resource_desc} '{resource_id}'"

    if isinstance(error, SmartLinkNotFoundError):
        return ToolError(
            f"SmartLink {resource_desc} not found. Verify the ID is correct."
        )
    if isinstance(error, SmartLinkAuthError):
        return ToolError(
            f"SmartLink authentication expired for {resource_desc}. "
            f"Run smartlink_auth_login to re-authenticate."
        )
    if isinstance(error, SmartLinkForbiddenError):
        # Flows/actions require bot or sysadmin; audits require sysadmin
        role_hint = "sysadmin" if resource_type == "audit" else "bot or sysadmin"
        return ToolError(
            f"Insufficient permissions for {resource_desc}. "
            f"The authenticated user needs the {role_hint} role."
        )
    if isinstance(error, SmartLinkValidationError):
        return ToolError(f"SmartLink validation failed for {resource_desc}: {error}")
    if isinstance(error, SmartLinkServerError):
        return ToolError(
            f"SmartLink server error for {resource_desc}: {error}. "
            f"This is a backend issue — retry later."
        )
    return ToolError(f"SmartLink error for {resource_desc}: {error}")
