from __future__ import annotations

import logging
from typing import Any, Literal

import requests


DEFAULT_TIMEOUT = 15
HttpMethod = Literal["GET", "POST", "PUT", "PATCH", "DELETE"]

logger = logging.getLogger(__name__)

class ApiError(RuntimeError):
    def __init__(self, message: str, *, url: str | None = None, status_code: int | None = None) -> None:
        super().__init__(message)
        self.url = url
        self.status_code = status_code


def http_request(
    method: HttpMethod,
    url: str,
    *,
    headers: dict[str, str] | None = None,
    params: dict[str, Any] | None = None,
    data: dict[str, Any] | None = None,
    json: dict[str, Any] | None = None,
    timeout: int = DEFAULT_TIMEOUT,
) -> requests.Response:
    try:
        response = requests.request(
            method=method,
            url=url,
            headers=headers,
            params=params,
            data=data,
            json=json,
            verify=False,
            timeout=timeout,
        )
        response.raise_for_status()
        return response

    except requests.RequestException as exc:
        status_code = getattr(getattr(exc, "response", None), "status_code", None)
        logger.warning("HTTP %s failed for %s (%s)", method, url, status_code or "no-status")
        raise ApiError(
            f"Erreur HTTP sur {method} {url}",
            url=url,
            status_code=status_code,
        ) from exc


def http_get(
    url: str,
    *,
    headers: dict[str, str] | None = None,
    params: dict[str, Any] | None = None,
    timeout: int = DEFAULT_TIMEOUT,
) -> requests.Response:
    return http_request("GET", url, headers=headers, params=params, timeout=timeout)


def http_post(
    url: str,
    *,
    headers: dict[str, str] | None = None,
    data: dict[str, Any] | None = None,
    json: dict[str, Any] | None = None,
    timeout: int = DEFAULT_TIMEOUT,
) -> requests.Response:
    return http_request("POST", url, headers=headers, data=data, json=json, timeout=timeout)
