"""Custom exceptions for Dash AI Chat extension."""

from typing import Optional


class DashAIChatError(Exception):
    """Base exception for all Dash AI Chat errors."""

    def __init__(self, message: str, details: Optional[str] = None):
        """Initialize exception with message and optional details."""
        super().__init__(message)
        self.message = message
        self.details = details

    def __str__(self) -> str:
        """Return formatted error message."""
        if self.details:
            return f"{self.message}: {self.details}"
        return self.message


class AuthenticationError(DashAIChatError):
    """Raised when authentication fails."""

    pass


class ConfigurationError(DashAIChatError):
    """Raised when configuration is invalid or missing."""

    pass


# Authentication-specific exceptions
class OAuthClientError(AuthenticationError):
    """Raised when OAuth client operations fail."""

    pass


class TokenError(AuthenticationError):
    """Raised when token operations fail."""

    pass


class CredentialError(AuthenticationError):
    """Raised when credential operations fail."""

    pass


# Configuration-specific exceptions
class CloudConfigError(ConfigurationError):
    """Raised when cloud configuration operations fail."""

    pass


class EnvironmentError(ConfigurationError):
    """Raised when environment configuration is invalid."""

    pass


# Network-specific exceptions
class APIError(DashAIChatError):
    """Raised when API operations fail."""

    def __init__(
        self,
        message: str,
        status_code: Optional[int] = None,
        details: Optional[str] = None,
    ):
        """Initialize API error with optional status code."""
        super().__init__(message, details)
        self.status_code = status_code

    def __str__(self) -> str:
        """Return formatted error message with status code."""
        msg = self.message
        if self.status_code:
            msg = f"{msg} (HTTP {self.status_code})"
        if self.details:
            msg = f"{msg}: {self.details}"
        return msg


class NetworkError(DashAIChatError):
    """Raised when network operations fail."""

    pass


class TimeoutError(DashAIChatError):
    """Raised when operations timeout."""

    pass


# Chat-specific exceptions
class ChatError(DashAIChatError):
    """Raised when chat operations fail."""

    pass


class LLMError(ChatError):
    """Raised when LLM API calls fail."""

    pass


class AgentError(ChatError):
    """Raised when agent tool execution fails."""

    pass


# Entitlement-specific exceptions
class EntitlementError(DashAIChatError):
    """Raised when user lacks required entitlements."""

    pass
