from typing import Dict
from typing import List


def _flatten_dictionary(source_dict: Dict, target_dict: Dict, key: str, flatten_arrays: bool) -> Dict:
    """Private function to flatten a dictionary representing a JSON

    Args:
        source_dict: A Python dictionary containing a JSON representation
        target_dict: The target dictionary to contain the flatten JSON
        key: If a recursive call, the key of the parent object
        flatten_arrays: A flag indicating whether arrays should be flattened as well. Only the first element of the array would be picked

    Returns:
        A dictionary with the representation of the flatten JSON
    """
    for k, v in source_dict.items():
        dict_key = k if len(key.strip()) == 0 else key + "." + k

        if isinstance(v, dict):
            for nested_k, nested_v in _flatten_dictionary(v, target_dict, dict_key, flatten_arrays).items():
                target_dict[nested_k] = nested_v
        else:
            value_is_list = isinstance(v, List)

            if dict_key in target_dict:
                if flatten_arrays:
                    target_dict[dict_key] = v[0] if value_is_list else v
                else:
                    if value_is_list:
                        target_dict[dict_key].extend(v)
                    else:
                        target_dict[dict_key].append(v)
            else:
                if flatten_arrays:
                    target_dict[dict_key] = v[0] if value_is_list else v
                else:
                    target_dict[dict_key] = v

    return target_dict