from typing import Optional
from typing import List


def load_csv(
    filepath: str,
    title_row: bool,
    title_keys: Optional[List[str]] = None,
    sep: Optional[str] = "\t",
) -> List:
    """load csv file

    Args:
        filepath: filepath to load
        title_row: has title in the first row or not?
                   If true, it'll return a list of dict where keys are from
                   the title, otherwise a list of str list.
        title_keys: if not `title_row`, you can set the title keys yourself.
        sep: separation char
    """
    data = list()
    title_keys = title_keys if title_keys else []
    with open(filepath, "rt", encoding="utf-8") as fin:
        for idx, line in enumerate(fin):
            line_data = line.strip().split(sep)
            if title_row and idx == 0:
                title_keys = line_data
                continue
            if title_keys:
                if len(title_keys) != len(line_data):
                    raise RuntimeError(
                        f"len of title keys: {title_keys}"
                        f" does not match the line data in line {idx + 1}"
                        f" in file: {filepath}"
                    )
                ins = {}
                for col, key in zip(line_data, title_keys):
                    ins[key] = col
            else:
                ins = line_data
            data.append(ins)
    return data