"""
Utilities for extending DSSClient HTTP functionality.

This module provides helper functions to perform HTTP requests with custom headers,
particularly for cases where XSRF tokens and other browser headers need to be passed
to DSS API endpoints.
"""

import json
from typing import Any, Dict, Optional

from flask import has_request_context, request


def perform_http(
    client: Any,
    method: str,
    path: str,
    params: Optional[Dict[str, Any]] = None,
    body: Optional[Dict[str, Any]] = None,
    stream: bool = False,
    files: Optional[Any] = None,
    raw_body: Optional[str] = None,
    headers: Optional[Dict[str, str]] = None,
    include_request_headers: bool = True,
) -> Any:
    """
    Perform an HTTP request using DSSClient with support for custom headers.

    This function extends the DSSClient's internal _perform_http method to support
    passing custom headers, particularly XSRF tokens and cookies from the browser
    request context.

    Args:
        client: DSSClient instance from dataiku.api_client()
        method: HTTP method (GET, POST, PUT, DELETE, etc.)
        path: API path (e.g., "/flow/recipes/get-managed-folder-options-no-context")
        params: Optional query parameters
        body: Optional request body (will be JSON-encoded)
        stream: Whether to stream the response
        files: Optional files to upload
        raw_body: Optional raw body string (takes precedence over body)
        headers: Optional additional headers to include
        include_request_headers: If True and in Flask request context, include
            X-XSRF-TOKEN and Cookie headers from the current request

    Returns:
        Response object from requests library

    Example:
        >>> client = dataiku.api_client()
        >>> response = perform_http(
        ...     client=client,
        ...     method="POST",
        ...     path="/flow/recipes/get-managed-folder-options-no-context",
        ...     params={"projectKey": "TEST"},
        ... )
        >>> result = response.json()
    """
    from dataikuapi.utils import handle_http_exception

    # Prepare body
    if body is not None:
        body = json.dumps(body)
    if raw_body is not None:
        body = raw_body

    # Ensure headers exist
    if headers is None:
        headers = {}

    # If in Flask request context, optionally include browser headers
    if include_request_headers and has_request_context():
        # Extract XSRF token from request headers
        xsrf_token = request.headers.get("X-XSRF-TOKEN")
        if xsrf_token:
            headers["X-XSRF-TOKEN"] = xsrf_token

        # Extract Cookie header from request
        cookie_header = request.headers.get("Cookie")
        if cookie_header:
            headers["Cookie"] = cookie_header

    # Perform the HTTP request using the client's session
    http_res = client._session.request(
        method,
        "%s/dip/api%s" % (client.host, path),
        params=params,
        data=body,
        files=files,
        stream=stream,
        headers=headers,
        verify=client._session.verify,
    )

    handle_http_exception(http_res)
    return http_res


def current_request_login() -> Optional[str]:
    from flask import g

    if hasattr(g, "authIdentifier") and g.authIdentifier:
        return g.authIdentifier

    return None
