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

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

import json

import httpx


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

    Handles non-JSON responses and missing fields gracefully.
    """
    try:
        body = response.json()
        error = body.get("error", {})
        if isinstance(error, dict):
            return str(error.get("message", response.text))
        return str(error)
    except (json.JSONDecodeError, ValueError):
        return response.text
