"""Patch httpx to propagate X-Request-ID on all outgoing requests.

Mirrors the approach in requests.py but uses httpx's event_hooks mechanism
to inject the header from the request_id_var context variable.
"""

import logging

import httpx

from . import request_id_var

logger = logging.getLogger(__name__)


def _inject_request_id(request: httpx.Request) -> None:
    """Event hook that injects X-Request-ID into outgoing httpx requests."""
    request_id = request_id_var.get()
    if request_id:
        request.headers["X-Request-ID"] = request_id
        logger.debug(
            "Injecting request_id %s into outgoing httpx request to %s",
            request_id,
            request.url,
        )


async def _inject_request_id_async(request: httpx.Request) -> None:
    """Async event hook for httpx.AsyncClient."""
    request_id = request_id_var.get()
    if request_id:
        request.headers["X-Request-ID"] = request_id
        logger.debug(
            "Injecting request_id %s into outgoing httpx request to %s",
            request_id,
            request.url,
        )


def patch_httpx():
    """Patch httpx.AsyncClient and httpx.Client to inject X-Request-ID.

    Monkeypatches __init__ on both client classes to prepend our event hook
    to the 'request' event_hooks list.
    """
    _original_async_init = httpx.AsyncClient.__init__
    _original_sync_init = httpx.Client.__init__

    def _patched_async_init(self, *args, **kwargs):
        _original_async_init(self, *args, **kwargs)
        self.event_hooks.setdefault("request", []).insert(0, _inject_request_id_async)

    def _patched_sync_init(self, *args, **kwargs):
        _original_sync_init(self, *args, **kwargs)
        self.event_hooks.setdefault("request", []).insert(0, _inject_request_id)

    httpx.AsyncClient.__init__ = _patched_async_init
    httpx.Client.__init__ = _patched_sync_init


__all__ = ["patch_httpx"]
