"""
Tools for executing shell commands
"""

import logging
import shlex
import subprocess

LOGGER = logging.getLogger(__name__)


def run_shell_command(command_line, *args, **kwargs):
    """
    Executes a shell command.

    Args:
        command_line (str): The shell command to be executed.
        *args: Additional positional arguments to pass to subprocess.check_call.
        **kwargs: Additional keyword arguments to pass to subprocess.check_call.

    Returns:
        int: The return code of the command executed.

    Raises:
        subprocess.CalledProcessError: If the command returns a non-zero exit status.
    """

    command_line_args = shlex.split(command_line)
    LOGGER.debug("🍪 Running command '%s'", command_line)
    return subprocess.check_call(command_line_args, *args, **kwargs)


def run_shell_command_with_output(command_line, *args, **kwargs) -> str:
    """
    Executes a shell command and returns its output.

    Args:
        command_line (str): The shell command to be executed.
        *args: Additional positional arguments to pass to subprocess.check_output.
        **kwargs: Additional keyword arguments to pass to subprocess.check_output.

    Returns:
        str: The output of the command executed, decoded to a UTF-8 string
            and stripped of trailing newline.

    Raises:
        subprocess.CalledProcessError: If the command returns a non-zero exit status.
    """

    command_line_args = shlex.split(command_line)
    LOGGER.debug("🍪 Running command '%s'", command_line)
    return subprocess.check_output(command_line_args, *args, **kwargs).decode("utf-8").rstrip("\n")
