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

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

import json
import logging
import urllib.parse
from typing import TYPE_CHECKING

import httpx
import typer
from rich.console import Console

if TYPE_CHECKING:
    from huitzo_cli.auth import AuthClient

logger = logging.getLogger(__name__)
_console = Console()


def get_auth() -> tuple["AuthClient", str, str]:
    """Get auth client, token, and API URL. Raises Exit if not authenticated.

    Enforces HTTPS for non-localhost targets (defense-in-depth).
    """
    from huitzo_cli.auth import AuthClient
    from huitzo_cli.config import ConfigManager

    config = ConfigManager()
    auth = AuthClient(config)
    token = auth.get_token()
    if not token:
        _console.print("[red]Not authenticated. Run: huitzo login[/red]")
        raise typer.Exit(1)
    api_url = auth.get_api_url()
    # Enforce HTTPS for non-localhost targets (defense-in-depth)
    if not api_url.startswith("https://"):
        parsed = urllib.parse.urlparse(api_url)
        if parsed.hostname not in ("localhost", "127.0.0.1", "::1"):
            _console.print("[red]HTTPS required for API calls. Check your config.[/red]")
            raise typer.Exit(1)
    return auth, token, api_url


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}"
