from typing import List


def split_to_sublists(initial_list:list, n:int, strict:bool=True) -> List[list]:
    """Takes a list and splits it into sublists of size n

    Parameters
    ----------
    initial_list : list
        The initial list to split into sublists

    n : int
        The size of each sublist

    strict: bool
        Whether to force an error if the length of the initial list is not divisible by n (split into even groups), default True

    Returns
    -------
    List[list]
        A list of lists of size n (unless strict is False, then the last list may be > n)

    Examples
    --------

    ### Split gallery images into sublists of 3

    #### JINJA USAGE
    ```jinja2
    {% if gallery|length % 3 == 0 %}
    {% for sublist in gallery|split_to_sublists(3) %}
        <div class="row">

        <div class="col-md-4">
            <img src="{{ sublist.0[0]['file_path'] }}" alt="{{ sublist.0[0]['file_path'].split()[-1] }}">
        </div>

        <div class="col-md-4">
            <img src="{{ sublist.1[0]['file_path'] }}" alt="{{ sublist.1[0]['file_path'].split()[-1]}}">
        </div>

        <div class="col-md-4">
            <img src="{{ sublist.2[0]['file_path'] }}" alt="{{ sublist.2[0]['file_path'].split()[-1] }}">
        </div>

        </div>
    {% endfor %}
    {% endif }
    ```

    The above jinja is roughly equivalent to something like this in pure python:

    ```python
    gallery = ["image 1" , "image 2", "image 3", "image 4" , "image 5", "image 6"]

    if len(images) % 3 == 0:
        for sublist in split_to_sublists(gallery, 3): # Returns [["image 1" , "image 2", "image 3"], ["image 4" , "image 5", "image 6"]]
        ... # Do stuff with each sublist
    ```
    """
    if strict:
        if not len(initial_list) % n == 0:
            raise ValueError(f"Provided list was not of correct size: \n\tList: {initial_list}\n\tSegment size {n}")

    result = []

    for i in range(0, len(initial_list), n): # Create sublists up to size n 
        result.append( initial_list[i:i + n])

    return result