"""
This module contains list-to-kw mangling helpers.
"""

from __future__ import annotations

from moat.lib.micro import Mapping

from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from collections.abc import MutableMapping
    from typing import Any

__all__ = ["pop_kw", "push_kw"]


def push_kw(args: list[Any], kwargs: dict[str, Any], is_warn: bool = False) -> None:
    """
    Add kwargs to the list, if required.

    Args:
        args:
            The argument list.
        kwargs:
            The argument mapping to (possibly) append.
        is_warn:
            This message is a user-level warning.

    The mapping is appended if
    - it is not empty.
    - the last argument is a mapping.
    - the argument of a user-level warning consists of a single integer.
    """
    if (
        kwargs
        or (args and isinstance(args[-1], dict))
        or (is_warn and len(args) == 1 and isinstance(args[0], int))
    ):
        args.append(kwargs if isinstance(kwargs, dict) else {})


def pop_kw(ak: list[Any]) -> MutableMapping[str, Any]:
    """
    Unpack an args-and-maybe-trailing-kwargs list.

    This function removes (and returns) an argument lists's trailing mapping, if any.
    Otherwise the result is an empty dict.

    Args:
        ak: Argument list, as generated by `push_kw`:

    Returns:
        The trailing mapping, or an empty dict.
    """
    if ak and isinstance(ak[-1], Mapping):
        return ak.pop()
    return {}
