# file: integrations/requests.py

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

# Variable to ensure patching is only done once
_instrumented = False


def instrument():
    """
    Applies monkey patching to the 'requests' library to automatically
    create trace spans for outgoing HTTP requests.
    """
    global _instrumented
    if _instrumented:
        return

    try:
        import requests
    except ImportError:
        logger.debug("'requests' library not found, skipping instrumentation.")
        return

    # Save reference to the original 'send' method of Session
    original_send = requests.Session.send

    # Define the new instrumented 'send' method
    def instrumented_send(self, request, **kwargs):
        # Never trace our own telemetry client's traffic (infinite-loop guard),
        # and do nothing when telemetry is not active (client may be None).
        client = get_current_client()
        if (
            client is not None
            and client.config.collector_url
            and 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)

        # Create a descriptive span name
        span_name = f"HTTP {request.method} {request.url}"

        # Wrap the original function call with trace_span
        with trace_span(
            span_name,
            attributes={"http.method": request.method, "http.url": request.url},
        ):
            # Call the original 'send' function
            response = original_send(self, request, **kwargs)

        return response

    # Replace the original 'send' method with our version
    requests.Session.send = instrumented_send

    _instrumented = True
