"""Curl debug output for HTTP requests.

When PINECONE_DEBUG_CURL=true is set, prints the equivalent curl command
and raw response for each HTTP request to stderr.
"""

from __future__ import annotations

import os
import sys

from typing import TYPE_CHECKING


if TYPE_CHECKING:
    import httpx

# Read once at import time; zero cost when False (just a bool check per request)
CURL_DEBUG_ENABLED: bool = os.environ.get("PINECONE_DEBUG_CURL", "").lower() == "true"

_REDACTED_HEADERS = frozenset({"api-key"})


def _shell_quote(s: str) -> str:
    """Escape a string for use inside single-quoted shell arguments.

    Replaces each single quote with the sequence '\\'' which ends the current
    single-quoted string, adds an escaped single quote, and reopens the
    single-quoted string.
    """
    return s.replace("'", "'\\''")


def format_curl_command(
    method: str,
    url: str,
    headers: dict[str, str],
    content: bytes | str | None,
) -> str:
    """Build an equivalent curl command string from request parameters.

    Args:
        method: HTTP method (GET, POST, etc.)
        url: Request URL
        headers: Request headers (Api-Key will be redacted)
        content: Request body (bytes or str), or None

    Returns:
        Formatted curl command string
    """
    parts: list[str] = [f"curl -X {method} '{_shell_quote(url)}'"]

    for name, value in headers.items():
        display_value = "$PINECONE_API_KEY" if name.lower() in _REDACTED_HEADERS else value
        parts.append(f"  -H '{_shell_quote(name)}: {_shell_quote(display_value)}'")

    if content is not None:
        body = content.decode("utf-8") if isinstance(content, bytes) else content
        parts.append(f"  -d '{_shell_quote(body)}'")

    return " \\\n".join(parts)


def print_curl_debug(
    method: str,
    url: str,
    headers: dict[str, str],
    content: bytes | str | None,
) -> None:
    """Print a curl command to stderr."""
    cmd = format_curl_command(method, url, headers, content)
    sys.stderr.write(f"\n> {cmd.replace(chr(10), chr(10) + '> ')}\n")
    sys.stderr.flush()


def print_response_debug(response: httpx.Response) -> None:
    """Print response status, headers, and body to stderr."""
    protocol = "HTTP/2" if response.http_version == "HTTP/2" else response.http_version
    sys.stderr.write(f"< {protocol} {response.status_code}\n")

    for name, value in response.headers.items():
        sys.stderr.write(f"< {name}: {value}\n")

    body = response.text
    if body:
        sys.stderr.write(f"< {body}\n")

    sys.stderr.flush()
