"""A wrapper for a HTTPx Client, which logs the calls under the debug log level."""

import logging
import time

from httpx import Client, Request, Response

logger = logging.getLogger(__name__)


def _time_in_logs() -> str:
    """Return the time for use in logging.

    This is milliseconds since epoch.
    """
    return str(int(time.time() * 1000))


def _log_request(request: Request):
    logger.debug("%s HTTP call start: %s %s", _time_in_logs(), request.method, request.url)


def _log_response(response: Response):
    request = response.request
    logger.debug(
        "%s HTTP call ended: %s %s - Response Status %s - Content-Length %s",
        _time_in_logs(),
        request.method,
        request.url,
        response.status_code,
        response.headers.get("Content-Length", "unknown"),
    )


def enable_httpx_client_logging(client: Client) -> Client:
    """Enable logging of all requests on the given httpx.Client."""
    client.event_hooks["request"] = [_log_request]
    client.event_hooks["response"] = [_log_response]
    return client


# usage:
#    enable_httpx_client_logging(client)
# or
#    client = enable_httpx_client_logging(Client(...))
