"""Exceptions for the Kawaa SDK."""

from typing import Any, Dict, Optional


class KawaaError(Exception):
    """Base exception for all Kawaa errors."""

    def __init__(
        self,
        message: str,
        status_code: Optional[int] = None,
        response_body: Optional[Dict[str, Any]] = None,
    ):
        super().__init__(message)
        self.message = message
        self.status_code = status_code
        self.response_body = response_body or {}

    def __str__(self) -> str:
        if self.status_code:
            return f"[{self.status_code}] {self.message}"
        return self.message


class AuthenticationError(KawaaError):
    """Raised when API key is invalid or missing."""

    pass


class RateLimitError(KawaaError):
    """Raised when rate limit is exceeded."""

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


class InsufficientCreditsError(KawaaError):
    """Raised when user doesn't have enough credits."""

    pass


class ValidationError(KawaaError):
    """Raised when request validation fails."""

    pass


class NotFoundError(KawaaError):
    """Raised when a resource is not found."""

    pass


class ServerError(KawaaError):
    """Raised when server encounters an error."""

    pass


class TimeoutError(KawaaError):
    """Raised when a request times out."""

    pass


class JobNotCompleteError(KawaaError):
    """Raised when trying to download results from an incomplete job."""

    def __init__(self, job_id: str, status: str, **kwargs: Any):
        message = f"Job {job_id} is not complete (status: {status})"
        super().__init__(message, **kwargs)
        self.job_id = job_id
        self.job_status = status


def raise_for_status(status_code: int, response_body: Dict[str, Any]) -> None:
    """Raise appropriate exception based on status code."""
    error_message = response_body.get("error", response_body.get("message", "Unknown error"))

    if status_code == 401:
        raise AuthenticationError(
            error_message,
            status_code=status_code,
            response_body=response_body,
        )
    elif status_code == 402:
        raise InsufficientCreditsError(
            error_message,
            status_code=status_code,
            response_body=response_body,
        )
    elif status_code == 404:
        raise NotFoundError(
            error_message,
            status_code=status_code,
            response_body=response_body,
        )
    elif status_code == 422:
        raise ValidationError(
            error_message,
            status_code=status_code,
            response_body=response_body,
        )
    elif status_code == 429:
        retry_after = response_body.get("retry_after")
        raise RateLimitError(
            error_message,
            status_code=status_code,
            response_body=response_body,
            retry_after=retry_after,
        )
    elif status_code >= 500:
        raise ServerError(
            error_message,
            status_code=status_code,
            response_body=response_body,
        )
    elif status_code >= 400:
        raise KawaaError(
            error_message,
            status_code=status_code,
            response_body=response_body,
        )
