# file: integrations/httpx.py

from ..apiTelemetry import get_current_client, inject_trace_id, logger, trace_span

_instrumented = False


def instrument():
    """Applies monkey patching to the 'httpx' library for both sync and async clients."""
    global _instrumented
    if _instrumented:
        return

    try:
        from httpx import AsyncClient, Client, Request  # type: ignore[import-not-found]
    except ImportError:
        logger.debug("'httpx' library not found, skipping instrumentation.")
        return

    # --- Sync Client Patching ---
    original_send = Client.send

    def instrumented_send(self, request: Request, **kwargs):
        """Wrapper for the synchronous httpx Client.send method."""
        client = get_current_client()
        if (
            client
            and client.config.collector_url
            and str(request.url).startswith(client.config.collector_url)
        ):
            return original_send(self, request, **kwargs)

        # Propagate the current trace id to the downstream service.
        inject_trace_id(request.headers)

        span_name = f"HTTP {request.method} {request.url}"
        attributes = {"http.method": request.method, "http.url": str(request.url)}

        with trace_span(span_name, attributes=attributes):
            response = original_send(self, request, **kwargs)
        return response

    # --- Async Client Patching ---
    original_async_send = AsyncClient.send

    async def instrumented_async_send(self, request: Request, **kwargs):
        """Wrapper for the asynchronous httpx AsyncClient.send method."""
        client = get_current_client()
        if (
            client
            and client.config.collector_url
            and str(request.url).startswith(client.config.collector_url)
        ):
            return await original_async_send(self, request, **kwargs)

        # Propagate the current trace id to the downstream service.
        inject_trace_id(request.headers)

        span_name = f"HTTP {request.method} {request.url}"
        attributes = {"http.method": request.method, "http.url": str(request.url)}

        with trace_span(span_name, attributes=attributes):
            response = await original_async_send(self, request, **kwargs)
        return response

    # Apply the patches
    Client.send = instrumented_send
    AsyncClient.send = instrumented_async_send
    _instrumented = True
