from typing import Sequence
from typing import List


def chunk_arguments(args: Sequence[str], arg_max: int = 16 * 1024, argc_max=1024) -> List[List[str]]:
    """
    Split a long list of command-line arguments into chunks.

    This is needed in order not to overflow the maximum length of the command-line arguments.

    :param args: command-line arguments
    :param arg_max: maximum length of the command-line arguments (i.e. the result of ``getconf ARG_MAX``)
    :param argc_max: maximum number of command-line arguments
    :return: chunked command-line arguments
    """
    for i, arg in enumerate(args):
        if len(arg) > arg_max:
            if len(arg) > 50:
                arg_str = arg[:50] + " [...]"
            else:
                arg_str = arg

            raise ValueError("The command-line argument {} is longer than allowed maximum length {}: {}".format(
                i, arg_max, arg_str))

    chunks = []  # type: List[List[str]]
    chunk_size = 0

    # latest chunk
    chunk = []  # type: List[str]
    for arg in args:
        if len(arg) + chunk_size > arg_max or chunk_size > argc_max:
            chunks.append(chunk)
            chunk = []
            chunk_size = 0

        chunk.append(arg)
        chunk_size += len(arg)
        if len(chunk) > 1:
            chunk_size += 1  # + 1 for white-space

    if len(chunk) > 0:
        chunks.append(chunk)

    return chunks