from __future__ import annotations

from typing import Any, Optional, Union


class A3ApiError(Exception):
    """Base error for all A3 API errors with an HTTP status code."""

    def __init__(
        self,
        message: str,
        status_code: int,
        body: Optional[dict[str, Any]] = None,
    ) -> None:
        super().__init__(message)
        self.status_code = status_code
        self.body = body


class A3AuthenticationError(A3ApiError):
    """Raised on 401 Unauthorized responses."""

    def __init__(self, body: Optional[dict[str, Any]] = None) -> None:
        raw = body.get("message", "Unauthorized") if body else "Unauthorized"
        msg = ", ".join(raw) if isinstance(raw, list) else str(raw)
        super().__init__(msg, 401, body)


class A3RateLimitError(A3ApiError):
    """Raised on 429 Too Many Requests responses."""

    def __init__(
        self,
        retry_after: Optional[float] = None,
        body: Optional[dict[str, Any]] = None,
    ) -> None:
        super().__init__("Rate limit exceeded", 429, body)
        self.retry_after = retry_after


class A3ValidationError(A3ApiError):
    """Raised on 400 Bad Request responses with validation details."""

    def __init__(self, body: Optional[dict[str, Any]] = None) -> None:
        raw: Union[str, list[str]] = (body or {}).get("message", [])
        self.validation_errors: list[str] = (
            raw if isinstance(raw, list) else [raw] if raw else []
        )
        msg = (
            f"Validation failed: {', '.join(self.validation_errors)}"
            if self.validation_errors
            else "Validation failed"
        )
        super().__init__(msg, 400, body)


class A3ConnectionError(Exception):
    """Raised on network or timeout errors (no HTTP status code)."""

    def __init__(self, message: str, cause: Optional[BaseException] = None) -> None:
        super().__init__(message)
        self.__cause__ = cause
