import re
import shlex


def command_fix(kernel_command):
    """
    Check the command for anything that might cause upset when it gets run
    by bash.

    Current checks are:
        IRkernel:main() needs escaping.
        Warn for any brackets
        Warn for unpaired quotes

    Parameters
    ----------
    kernel_command : str
        The kernel command that is run by bash.

    Returns
    -------
    fixed_kernel_command : srt
        The kernel command with any fixes applied.

    """
    # IRKernel:main() fix
    # if not escaped or quoted then bash trips up on the brackets
    if " IRkernel::main()" in kernel_command:
        kernel_command = kernel_command.replace(
            " IRkernel::main()", " 'IRkernel::main()'"
        )
        print("Escaping IRkernel::main().")

    # Unescaped brackets
    if re.search(r"[^\\][()]", kernel_command) and not re.search(
        r"[\'\"].*[^\\][()].*[\'\"]", kernel_command
    ):
        print("Warning: possibly unescaped brackets in the kernel command.")

    try:
        shlex.split(kernel_command)
    except ValueError:
        print("Kernel command may be missing quotation marks.")

    return kernel_command