"""
— SDK Utility Functions
=============================================
Small helpers used across multiple modules.
Nothing here has side effects; all functions are pure.
"""

from __future__ import annotations

import os
from typing import Optional


def resolve_api_key(explicit_key: Optional[str] = None) -> str:
    """
    Resolve the API key from:
      1. Explicit argument (highest priority)
      2. NEES_API_KEY environment variable
      3. Raise ValueError if neither is set

    Args:
        explicit_key — value passed directly to Client(api_key=...)

    Returns:
        The resolved API key string.

    Raises:
        ValueError — if no key is found.
    """
    key = explicit_key or os.environ.get("NEES_API_KEY", "").strip()
    if not key:
        raise ValueError(
            "No API key found. Either:\n"
            "  1. Pass it directly:  Client(api_key='your-key')\n"
            "  2. Set environment:   export NEES_API_KEY='your-key'"
        )
    return key


def truncate(text: str, max_len: int = 80, suffix: str = "…") -> str:
    """Truncate text for display, appending suffix if truncated."""
    if len(text) <= max_len:
        return text
    return text[: max_len - len(suffix)] + suffix


def safe_float(value: object, default: float = 0.0) -> float:
    """Cast value to float, returning default on failure."""
    try:
        return float(value)  # type: ignore[arg-type]
    except (TypeError, ValueError):
        return default


def safe_int(value: object, default: int = 0) -> int:
    """Cast value to int, returning default on failure."""
    try:
        return int(value)  # type: ignore[arg-type]
    except (TypeError, ValueError):
        return default
