from typing import Iterable
from typing import Sequence
from pathlib import Path
from typing import Optional
import csv


def write_list_to_csv(
    data: Iterable[Sequence],
    file_path: Path,
    parents=False,
    exist_ok=True,
    has_header: bool = True,
    headers: Optional[Sequence[str]] = None,
) -> int:
    """
    Writes an iterator of lists to a file in csv format.

    Parameters
    ----------
    data : Iterable[Sequence]
        [description]
    file_path : Path
        [description]
    parents : bool, optional
        [description], by default False
    exist_ok : bool, optional
        [description], by default True
    has_header : bool, optional
        First row of supplied data is the header, by default True
    headers : Optional[Sequence[str]], optional
        Headers to use if not supplied in data, by default None

    Returns
    -------
    int
        Rows saved, not including a header

    Raises
    ------
    ValueError
        Number of items in a row does not match number of headers.
    """
    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.writer(file_out)
        iterable_data = iter(data)

        if has_header:
            header_row = next(iterable_data)
            writer.writerow(header_row)
        else:
            if headers is not None:
                header_row = headers
                writer.writerow(header_row)
            else:
                header_row = []
        total_count = 0
        for count, item in enumerate(iterable_data):
            if count > 0 and has_header:
                if len(header_row) > 0 and len(header_row) != len(item):
                    raise ValueError(
                        f"Header has {len(header_row)} but row has {len(item)} items"
                    )
                writer.writerow(item)
                total_count = count
    return total_count + 1