"""Shared asynchronous HTTP clients, imported only when configured."""

from __future__ import annotations

import asyncio
from dataclasses import dataclass, field
from typing import Any


class HttpDependencyError(RuntimeError):
    """Raised when an HTTP connector is used without the HTTP extra."""


@dataclass(frozen=True, slots=True)
class HttpClientSettings:
    base_url: str
    timeout_s: float = 5.0
    headers: tuple[tuple[str, str], ...] = field(default_factory=tuple)
    verify_tls: bool = True


class HttpClientPool:
    def __init__(self) -> None:
        self._clients: dict[str, Any] = {}
        self._settings: dict[str, HttpClientSettings] = {}
        self._lock = asyncio.Lock()

    async def get(self, endpoint_id: str, settings: HttpClientSettings) -> Any:
        async with self._lock:
            existing = self._clients.get(endpoint_id)
            if existing is not None:
                if self._settings[endpoint_id] != settings:
                    raise ValueError(
                        f"HTTP endpoint {endpoint_id!r} requested with conflicting settings"
                    )
                return existing

            try:
                import httpx
            except ImportError as exc:
                raise HttpDependencyError(
                    "HTTP support is not installed; install cmvr-edge-ai[http]"
                ) from exc

            client = httpx.AsyncClient(
                base_url=settings.base_url,
                timeout=settings.timeout_s,
                headers=dict(settings.headers),
                verify=settings.verify_tls,
            )
            self._clients[endpoint_id] = client
            self._settings[endpoint_id] = settings
            return client

    async def close(self) -> None:
        async with self._lock:
            clients = tuple(self._clients.values())
            self._clients.clear()
            self._settings.clear()
        await asyncio.gather(
            *(client.aclose() for client in clients), return_exceptions=True
        )
