from __future__ import annotations

from typing import Any

import httpx

from .config import HTTP_TIMEOUT, USER_AGENT


class ExternalApiError(RuntimeError):
    """Erreur standardisée pour les appels aux API publiques."""


def get_json(url: str, params: dict[str, Any] | None = None, timeout: float | None = None) -> Any:
    headers = {"User-Agent": USER_AGENT, "Accept": "application/json"}
    try:
        with httpx.Client(timeout=timeout or HTTP_TIMEOUT, follow_redirects=True, headers=headers) as client:
            response = client.get(url, params=params)
            response.raise_for_status()
            return response.json()
    except Exception as exc:  # noqa: BLE001 - on normalise les erreurs d'API externes
        raise ExternalApiError(f"Impossible d'appeler {url}: {exc}") from exc


def get_text(url: str, params: dict[str, Any] | None = None, timeout: float | None = None) -> str:
    headers = {"User-Agent": USER_AGENT}
    try:
        with httpx.Client(timeout=timeout or HTTP_TIMEOUT, follow_redirects=True, headers=headers) as client:
            response = client.get(url, params=params)
            response.raise_for_status()
            return response.text
    except Exception as exc:  # noqa: BLE001
        raise ExternalApiError(f"Impossible d'appeler {url}: {exc}") from exc
