"""Octen SDK 异常定义"""

from typing import Optional, Dict, Any


class OctenError(Exception):
    """Octen SDK 基础异常类"""

    def __init__(self, message: str, **kwargs):
        super().__init__(message)
        self.message = message
        for key, value in kwargs.items():
            setattr(self, key, value)


class OctenAPIError(OctenError):
    """API 请求错误

    Attributes:
        message: 错误消息
        status_code: HTTP 状态码
        response_data: 原始响应数据
        request_id: 请求 ID（如果有）
    """

    def __init__(
        self,
        message: str,
        status_code: Optional[int] = None,
        response_data: Optional[Dict[str, Any]] = None,
        request_id: Optional[str] = None,
    ):
        super().__init__(message)
        self.status_code = status_code
        self.response_data = response_data
        self.request_id = request_id

    def __str__(self):
        parts = [self.message]
        if self.status_code:
            parts.append(f"Status: {self.status_code}")
        if self.request_id:
            parts.append(f"Request ID: {self.request_id}")
        return " | ".join(parts)


class OctenTimeoutError(OctenError):
    """请求超时错误"""

    def __init__(self, message: str = "Request timed out", timeout: Optional[float] = None):
        super().__init__(message)
        self.timeout = timeout

    def __str__(self):
        if self.timeout:
            return f"{self.message} (timeout: {self.timeout}s)"
        return self.message


class OctenConnectionError(OctenError):
    """连接错误"""

    def __init__(self, message: str = "Connection error occurred"):
        super().__init__(message)


class OctenValidationError(OctenError):
    """数据验证错误"""

    def __init__(self, message: str, errors: Optional[list] = None):
        super().__init__(message)
        self.errors = errors or []

    def __str__(self):
        if self.errors:
            error_details = "; ".join(str(e) for e in self.errors)
            return f"{self.message}: {error_details}"
        return self.message


class OctenRateLimitError(OctenAPIError):
    """请求速率限制错误"""

    def __init__(
        self,
        message: str = "Rate limit exceeded",
        retry_after: Optional[int] = None,
        **kwargs,
    ):
        super().__init__(message, status_code=429, **kwargs)
        self.retry_after = retry_after


class OctenAuthenticationError(OctenAPIError):
    """认证错误"""

    def __init__(self, message: str = "Authentication failed", **kwargs):
        super().__init__(message, status_code=401, **kwargs)
