"""Graylog client error hierarchy and AI-friendly error translation."""

from __future__ import annotations

from fastmcp.exceptions import ToolError


class GraylogClientError(Exception):
    """Base error for all Graylog client operations."""

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


class GraylogAuthError(GraylogClientError):
    """401/403 — invalid credentials or insufficient permissions."""


class GraylogConnectionError(GraylogClientError):
    """Network-level connection failure."""


class GraylogTimeoutError(GraylogClientError):
    """Request timed out."""


class GraylogNotFoundError(GraylogClientError):
    """404 — resource not found."""


class GraylogServerError(GraylogClientError):
    """500+ — Graylog server error."""


def translate_error(
    error: Exception,
    *,
    resource_type: str | None = None,
    resource_id: str | int | None = None,
) -> ToolError:
    """Translate a Graylog 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, GraylogConnectionError):
        return ToolError(
            f"Graylog connection failed for {resource_desc}: {error}. "
            f"Check network access to the Graylog instance."
        )
    if isinstance(error, GraylogTimeoutError):
        return ToolError(
            f"Graylog request timed out for {resource_desc}: {error}. "
            f"Try a narrower time range or smaller limit."
        )
    if isinstance(error, GraylogAuthError):
        return ToolError(
            f"Graylog authentication failed for {resource_desc}. "
            f"Run graylog_auth_login to authenticate."
        )
    if isinstance(error, GraylogNotFoundError):
        return ToolError(
            f"Graylog {resource_desc} not found. "
            f"Use graylog_stream_list to discover available streams."
        )
    if isinstance(error, GraylogServerError):
        return ToolError(
            f"Graylog server error for {resource_desc}: {error}. "
            f"Check graylog_connection_status."
        )
    return ToolError(f"Graylog error for {resource_desc}: {error}")
