from typing import Sequence
from typing import Dict
from typing import Any
from pathlib import Path
import csv


def write_list_of_dicts_to_csv(
    data: Sequence[Dict[str, Any]], file_path: Path, parents=False, exist_ok=True
) -> int:
    """
    Save a list of dicts to csv. Makes parent directories if they don't exist.

    Parameters
    ----------
    data : Sequence[Dict[str, Any]]
        Data to save.
    file_path : Path
        Path to saved file. Existing files will be overwritten.
    parents : bool, optional
        Make parent directories if they don't exist. As used by `Path.mkdir`, by default False
    exist_ok : bool, optional
        Suppress exception if parent directory exists as directory. As used by `Path.mkdir`, by default True

    Returns
    -------
    int
        records writen.

    Raises
    ------
    Exception
        Any exception that can be raised from Path.mkdir or Path.open
    """
    if parents:
        file_path.parent.mkdir(parents=parents, exist_ok=exist_ok)
    with file_path.open("w", encoding="utf8", newline="") as file_out:
        writer = csv.DictWriter(file_out, fieldnames=list(data[0].keys()))
        writer.writeheader()
        total_count = 0
        for count, item in enumerate(data):
            writer.writerow(item)
            total_count = count
    return total_count + 1