from __future__ import annotations

from dataclasses import dataclass
from typing import Any, Optional


class SpecificAIError(Exception):
    """Base exception for the SpecificAI SDK."""


@dataclass
class APIErrorDetails:
    """Structured error info parsed from an HTTP response."""

    status_code: int
    message: str
    response_json: Optional[dict[str, Any]] = None
    response_text: Optional[str] = None
    request_id: Optional[str] = None


class SpecificAIAPIError(SpecificAIError):
    """Raised when the SpecificAI API returns an error response."""

    def __init__(self, details: APIErrorDetails):
        super().__init__(f"HTTP {details.status_code}: {details.message}")
        self.details = details

    @property
    def status_code(self) -> int:
        return self.details.status_code

    @property
    def response_json(self) -> Optional[dict[str, Any]]:
        return self.details.response_json


class AuthenticationError(SpecificAIAPIError):
    """401 Unauthorized."""


class PermissionDeniedError(SpecificAIAPIError):
    """403 Forbidden."""


class NotFoundError(SpecificAIAPIError):
    """404 Not Found."""


class RateLimitError(SpecificAIAPIError):
    """429 Too Many Requests."""


class ValidationError(SpecificAIAPIError):
    """400 / 422 validation errors."""


class ServerError(SpecificAIAPIError):
    """5xx server errors."""


class NetworkError(SpecificAIError):
    """Raised on network/transport errors before receiving an HTTP response."""

    def __init__(self, message: str, *, cause: Exception | None = None):
        super().__init__(message)
        self.__cause__ = cause
