"""
Module: http_utils
Description: Shared HTTP client utilities for safe response parsing.

Implements:
    - docs/cli/reference.md#error-handling
"""

import json
import logging

import httpx

logger = logging.getLogger(__name__)


def parse_error(response: httpx.Response) -> str:
    """Safely extract error message from an HTTP response.

    Returns a generic message on non-JSON responses to prevent leaking
    raw backend error bodies (stack traces, internal paths).
    Raw response text is logged at DEBUG level only.
    """
    try:
        body = response.json()
        error = body.get("error", {})
        if isinstance(error, dict):
            return str(error.get("message", f"HTTP {response.status_code}"))
        return str(error)
    except (json.JSONDecodeError, ValueError):
        logger.debug("Raw error response: %s", response.text)
        return f"HTTP {response.status_code}"
