"""Small utilities used across the package."""

from __future__ import annotations

from typing import Any, Iterable

from zenhub_client.exceptions import ZenhubError


def get_required(mapping: dict[str, Any], key: str) -> Any:
    """Return mapping[key] or raise a helpful error."""
    if key not in mapping:
        raise ZenhubError(f"Expected key '{key}' in response but it was missing.")
    return mapping[key]


def get_in(mapping: dict[str, Any], path: Iterable[str]) -> Any:
    """Traverse nested dicts using `path` and return the value.

    Raises a ZenhubError with context if the path does not exist.
    """
    cur: Any = mapping
    for key in path:
        if not isinstance(cur, dict):
            raise ZenhubError(f"Expected dict at '{key}' while traversing {list(path)}")
        if key not in cur:
            raise ZenhubError(f"Missing key '{key}' while traversing {list(path)}")
        cur = cur[key]
    return cur


def normalise_name(value: str) -> str:
    return " ".join(str(value).strip().lower().split())
