"""
Base HTTP transport using httpx.
"""

from __future__ import annotations

import json
from typing import TYPE_CHECKING

from fortytwo.logger import logger


if TYPE_CHECKING:
    import httpx

    from fortytwo.core.auth.tokens import Tokens
    from fortytwo.parameter import Parameter
    from fortytwo.resources.resource import Resource


class BaseTransport:
    """
    Base class for HTTP transports using httpx.
    """

    @staticmethod
    def _build_request_kwargs(
        resource: Resource,
        params: list[Parameter],
        tokens: Tokens,
        timeout: int | None,
    ) -> dict:
        return {
            "method": resource.method,
            "url": resource.url,
            "headers": {"Authorization": f"Bearer {tokens.access_token}"},
            "params": [param.to_query_param() for param in params],
            "timeout": timeout,
        }

    @staticmethod
    def _log_request(resource: Resource, params: list[Parameter]) -> None:
        query_params = [param.to_query_param() for param in params]
        logger.info(
            "Making request to %s?%s",
            resource.url,
            "&".join(f"{p[0]}={p[1]}" for p in query_params),
        )

    @staticmethod
    def _log_response(response: httpx.Response) -> None:
        logger.info("Received response (%d)", response.status_code)
        logger.debug("Response headers: %s", json.dumps(dict(response.headers), indent=2))

        try:
            response_json = response.json()
            logger.debug("Response content: %s", json.dumps(response_json, indent=2))
        except json.JSONDecodeError:
            logger.debug("Response content (non-JSON): %s", response.text[:1000])
