"""
Shared HTTP logic for sync and async clients.
"""

from __future__ import annotations

DEFAULT_BASE_URL = "https://api.agentphone.to"


class AgentPhoneError(Exception):
    """Raised when the AgentPhone API returns a non-2xx response."""

    def __init__(self, status: int, message: str):
        self.status = status
        self.message = message
        super().__init__(f"AgentPhone API error {status}: {message}")


class AuthenticationError(AgentPhoneError):
    pass


class NotFoundError(AgentPhoneError):
    pass


class RateLimitError(AgentPhoneError):
    pass


def _raise_for_status(status: int, text: str) -> None:
    try:
        import json as _json
        detail = _json.loads(text).get("detail") or _json.loads(text).get("message") or text
    except Exception:
        detail = text

    if status == 401:
        raise AuthenticationError(status, detail)
    if status == 404:
        raise NotFoundError(status, detail)
    if status == 429:
        raise RateLimitError(status, detail)
    raise AgentPhoneError(status, detail)
