import typing
import itertools


def _group_pipeline_runs_by_fold_group(
    pipeline_runs: typing.Sequence[typing.Dict[str, typing.Any]], default_group: str = '',
) -> typing.Dict[str, typing.Sequence[typing.Dict[str, typing.Any]]]:
    """
    Groups pipeline runs by pipeline_run.run.fold_group.id.

    Params
    ------
    pipeline_runs:
        The pipeline runs to group.
    default_group:
        Groups all pipeline runs that do not have a fold group under this key.

    Return
    ------
    grouped_pipeline_runs:
        The pipeline runs grouped by fold group id.
    """

    grouped_pipeline_runs: typing.Dict[str, typing.Sequence[typing.Dict[str, typing.Any]]] = {
        key: list(value) for key, value in itertools.groupby(
            pipeline_runs,
            lambda pipeline_run: pipeline_run['run'].get('fold_group', {}).get('id', default_group)
        )
    }

    assert sum(len(group) for group in grouped_pipeline_runs.values()) == len(pipeline_runs)

    return grouped_pipeline_runs