from typing import Union
from pathlib import Path
from typing import Optional
from typing import Dict
from typing import List


def get_csv_counts(
    file: Union[str, Path], separator: Optional[str] = None
) -> Dict[int, List[str]]:
    """
    Get groups of semantically consistsent csv lines.
    i.e. same number of commas

    Parameters
    ----------
        file : a string, pathlib.Path to used within a
               call to `open(file, "r") as f`.

        separator: (optional) a string indicating the token
                    that is to be taken as column delimiter.
                    it defaults to ","

    Returns
    -------
        A dictionnary containing the number of commas as keys
        and the lines which have said number of commas.
        i.e.

            {
                3: [
                    "x1,x2,x3",
                    "11,21,31",
                    "12,22,33",
                ],
                2: [
                    "extrainfo,date",
                    "none,2020-05-05"
                ]
            }
    """
    _separator: str = separator or ","

    with open(file, "r") as file_reader:
        lines: List[str] = file_reader.readlines()

    csv_counts: Dict[int, List[str]] = {}

    for line in lines:
        n_commas: int = line.count(_separator)
        if n_commas in csv_counts.keys():
            csv_counts[n_commas].append(line)
        else:
            csv_counts.update({n_commas: [line]})

    return csv_counts