"""
HS Mail SDK — Internal HTTP client.
Uses the `requests` library; wraps all HTTP calls and maps error codes to typed exceptions.
"""
from __future__ import annotations

import requests
from .exceptions import HsMailError, create_typed_error

SDK_VERSION = "1.0.0"


class HttpClient:
    def __init__(self, api_key: str, base_url: str, timeout: int = 30):
        self._base_url = base_url.rstrip("/")
        self._timeout = timeout
        self._session = requests.Session()
        self._session.headers.update({
            "Authorization": f"Bearer {api_key}",
            "Content-Type": "application/json",
            "Accept": "application/json",
            "User-Agent": f"HsMail-Python-SDK/{SDK_VERSION}",
        })

    def get(self, path: str) -> dict:
        return self._request("GET", path)

    def post(self, path: str, body: dict) -> dict:
        return self._request("POST", path, json=body)

    def _request(self, method: str, path: str, **kwargs) -> dict:
        url = f"{self._base_url}{path}"
        try:
            resp = self._session.request(method, url, timeout=self._timeout, **kwargs)
        except requests.exceptions.Timeout:
            raise HsMailError(
                f"Request timed out after {self._timeout}s", "TIMEOUT", 408
            )
        except requests.exceptions.RequestException as exc:
            raise HsMailError(str(exc), "NETWORK_ERROR", 0)

        try:
            data = resp.json()
        except ValueError:
            data = {}

        if not resp.ok:
            code = data.get("code", "UNKNOWN_ERROR")
            message = data.get("message", f"HTTP {resp.status_code}")
            raise create_typed_error(code, message, resp.status_code, data)

        # Unwrap `data` key when present
        return data.get("data", data)
