import typing
from typing import OrderedDict
import ast
import itertools


def _build_grid_search_commands(script: str, params: typing.Iterable[str]) -> typing.Iterable[typing.List[str]]:
    """
    Build all grid search parameter configurations.

    :param script: String of command prefix, e.g. ``emloop train -v -o log``.
    :param params: Iterable collection of strings in standard **emloop** param form, e.g. ``'numerical_param=[1, 2]'``
                   or ``'text_param=["hello", "cio"]'``.
    """

    param_space = OrderedDict()
    for arg in params:
        assert '=' in arg

        name = arg[:arg.index('=')]
        options = arg[arg.index('=') + 1:]
        options = ast.literal_eval(options)
        assert isinstance(options, list), options

        param_space[name] = options

    param_names = param_space.keys()
    commands = []
    for values in itertools.product(*[param_space[name] for name in param_names]):
        command = str(script).split()
        for name, value in zip(param_names, values):
            command.append(str(name) + '="' + str(value) + '"')
        commands.append(command)

    return commands