# file: integrations/aiohttp.py

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

_instrumented = False


def instrument():
    """Applies monkey patching to the 'aiohttp' library."""
    global _instrumented
    if _instrumented:
        return

    try:
        from aiohttp.client import ClientSession  # type: ignore[import-not-found]
    except ImportError:
        logger.debug("'aiohttp' library not found, skipping instrumentation.")
        return

    original_request = ClientSession._request

    async def instrumented_request(self, method, str_or_url, **kwargs):
        """Wrapper for aiohttp's _request method to create trace spans."""
        client = get_current_client()
        # Never trace our own client's traffic, and skip when telemetry is off.
        if (
            client
            and client.config.collector_url
            and str(str_or_url).startswith(client.config.collector_url)
        ):
            return await original_request(self, method, str_or_url, **kwargs)

        # Propagate the current trace id into the outgoing request headers.
        outgoing_headers = dict(kwargs.get("headers") or {})
        inject_trace_id(outgoing_headers)
        kwargs["headers"] = outgoing_headers

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

        with trace_span(span_name, attributes=attributes):
            # Call the original method and await the result
            response = await original_request(self, method, str_or_url, **kwargs)

        return response

    ClientSession._request = instrumented_request
    _instrumented = True
