def flatten(data: dict | list[dict]) -> dict | list[dict]:
    """Flatten a nested dictionary into a single-level dictionary.

    Parameters
    ----------
    data
        A dictionary or a list of dictionaries to flatten.

    Returns
    -------
    If `data` is a dictionary, returns a flattened dictionary.
    If `data` is a list of dictionaries, returns a list of flattened dictionaries.
    """
    if isinstance(data, dict):
        return _flatten(data)
    if isinstance(data, list):
        if not data:
            return []
        if not all(isinstance(item, dict) for item in data):
            raise ValueError("All items in the list must be dictionaries.")
        return [_flatten(item) for item in data]
    raise ValueError("Input must be a dictionary or a list of dictionaries.")


def _flatten(data, output: dict | None = None, path: str | None = None):
    output = output if output is not None else {}
    if isinstance(data, str | int | float | bool | None):
        output[path] = data
        return output
    if isinstance(data, dict):
        for key, value in data.items():
            new_path = _flatten_key(path, key)
            _flatten(data=value, output=output, path=new_path)
        return output
    if isinstance(data, list):
        if len(data) == 0:
            output[path] = None
            return output
        if all(isinstance(val, str | int | float | bool | None) for val in data):
            output[path] = data[0] if len(data) == 1 else data
            return output
        if len(data) != 1:
            raise ValueError(f"Data at {path} is a list with more than one non-primitive element: {data}")
        return _flatten(data=data[0], output=output, path=path)
    raise ValueError(f"Unknown data type {type(data)} at {path}")


def _flatten_key(path: str | None, key: str):
    if path:
        return f"{path}.{key}"
    return key
