"""Shared configuration utilities for ToRivers CLI commands."""

from __future__ import annotations

import json
import os
from pathlib import Path
from typing import Any

import httpx

PRODUCTION_API_BASE_URL = "https://app.torivers.com/api"
API_TIMEOUT_SECONDS = 30.0


def get_config_path() -> Path:
    """Get path to the ToRivers CLI config file."""
    return Path.home() / ".torivers" / "config.json"


def read_config() -> dict[str, Any]:
    """Read and parse ``~/.torivers/config.json``, returning ``{}`` on any error."""
    config_path = get_config_path()
    if not config_path.exists():
        return {}
    try:
        with open(config_path) as f:
            data = json.load(f)
        return data if isinstance(data, dict) else {}
    except (json.JSONDecodeError, OSError):
        return {}


def get_api_base_url() -> str:
    """
    Resolve the ToRivers API base URL.

    Resolution order:
      1. ``TORIVERS_API_URL`` environment variable
      2. ``~/.torivers/config.json`` -> ``api_base_url``
      3. Production default (``https://app.torivers.com/api``)
    """
    configured = os.environ.get("TORIVERS_API_URL")
    if configured and configured.strip():
        return configured.strip().rstrip("/")

    stored = read_config().get("api_base_url")
    if isinstance(stored, str) and stored.strip():
        return stored.strip().rstrip("/")

    return PRODUCTION_API_BASE_URL


def get_auth_url() -> str:
    """
    Resolve the ToRivers CLI authentication URL.

    Resolution order:
      1. ``TORIVERS_AUTH_URL`` environment variable (escape-hatch override)
      2. Derived from :func:`get_api_base_url`: strip ``/api``, append ``/auth/cli``
    """
    override = os.environ.get("TORIVERS_AUTH_URL")
    if override and override.strip():
        return override.strip().rstrip("/")

    base = get_api_base_url()
    app_origin = base.removesuffix("/api")
    return f"{app_origin}/auth/cli"


def is_authenticated() -> bool:
    """Check whether a valid auth token exists in config."""
    token = read_config().get("auth_token")
    return isinstance(token, str) and bool(token.strip())


def get_auth_token() -> str:
    """
    Retrieve the stored authentication token.

    Raises:
        RuntimeError: If no token is found.
    """
    token = read_config().get("auth_token")
    if not token or not isinstance(token, str) or not token.strip():
        raise RuntimeError("Not authenticated. Run 'torivers login' first.")
    return token.strip()


def extract_error_message(response: httpx.Response) -> str:
    """Extract a human-readable error message from an HTTP response."""
    try:
        data = response.json()
        if isinstance(data, dict):
            if data.get("error"):
                return str(data["error"])
            if data.get("message"):
                return str(data["message"])
    except (ValueError, TypeError):
        pass
    return response.text or f"HTTP {response.status_code}"
