"""Unified exception hierarchy for all Primitif products."""

from __future__ import annotations

from typing import TYPE_CHECKING

if TYPE_CHECKING:
    import httpx


class PrimitifError(Exception):
    """Base exception for all Primitif SDK errors."""

    def __init__(
        self,
        message: str = "",
        *,
        status_code: int = 0,
        code: str = "",
        response: "httpx.Response | None" = None,
        request_id: str | None = None,
    ) -> None:
        self.message = message
        self.status_code = status_code
        self.code = code
        self.response = response
        self.request_id = request_id
        if status_code:
            super().__init__(f"{status_code} {code}: {message}")
        else:
            super().__init__(message)


class AuthError(PrimitifError):
    """401 — invalid or missing credentials."""


class NotFoundError(PrimitifError):
    """404 — resource not found."""


class ConflictError(PrimitifError):
    """409 — resource conflict."""


class ValidationError(PrimitifError):
    """422 — invalid request payload."""


class RateLimitError(PrimitifError):
    """429 — rate limit exceeded."""

    @property
    def retry_after(self) -> float | None:
        """Seconds to wait before retrying, from the Retry-After header."""
        if self.response is not None:
            val = self.response.headers.get("retry-after")
            if val:
                try:
                    return float(val)
                except (ValueError, TypeError):
                    return None
        return None


class ServerError(PrimitifError):
    """5xx — server error."""


class NetworkError(PrimitifError):
    """Network-level failure — timeout, DNS, TCP, or TLS error."""


class InvalidSignature(PrimitifError):
    """Webhook signature verification failed."""
