"""Shared HTTP helper with timeout and connection reuse."""

import time
from typing import Any

import httpx

REQUEST_TIMEOUT = 6.0


async def send_request(
    client: httpx.AsyncClient,
    *,
    url: str,
    method: str = "POST",
    headers: dict[str, str] | None = None,
    body: Any = None,
    raw_body: str | None = None,
    content_type: str | None = None,
) -> dict:
    req_headers = dict(headers or {})
    if content_type:
        req_headers["Content-Type"] = content_type

    start = time.perf_counter()
    try:
        if raw_body is not None:
            resp = await client.request(
                method, url, headers=req_headers,
                content=raw_body.encode("utf-8", errors="replace"),
                timeout=REQUEST_TIMEOUT, follow_redirects=False,
            )
        elif body is not None:
            resp = await client.request(
                method, url, headers=req_headers,
                json=body, timeout=REQUEST_TIMEOUT, follow_redirects=False,
            )
        else:
            resp = await client.request(
                method, url, headers=req_headers,
                timeout=REQUEST_TIMEOUT, follow_redirects=False,
            )
        elapsed = (time.perf_counter() - start) * 1000
        return {
            "status_code": resp.status_code,
            "latency_ms": round(elapsed, 1),
            "error": None,
            "body": (resp.text[:2000] if resp.text else ""),
            "headers": dict(resp.headers),
        }
    except httpx.TimeoutException:
        elapsed = (time.perf_counter() - start) * 1000
        return {
            "status_code": None,
            "latency_ms": round(elapsed, 1),
            "error": "timeout",
            "body_snippet": "",
            "headers": {},
        }
    except Exception as exc:
        elapsed = (time.perf_counter() - start) * 1000
        return {
            "status_code": None,
            "latency_ms": round(elapsed, 1),
            "error": str(exc)[:200],
            "body_snippet": "",
            "headers": {},
        }
