from pathlib import Path
import csv


def read_distance_matrix(filepath=None):
    """
    Read a distance matrix, used to seed a regressor.

    Parameters
    ==========
    filepath : str
        Path to the TSV file containing the distance matrix used to
        seed the regressor. If not provided, will default to one derived
        from data presented in Mielke (2012) and included in the library.

    Returns
    =======
    matrix : dict
        A dictionary of dictionaries with the distances as floating-point
        values.
    """

    if not filepath:
        filepath = Path(__file__).parent.parent / "resources" / "distances"
        filepath = filepath / "mielke2012.tsv"
        filepath = filepath.as_posix()

    matrix = {}
    with open(filepath) as tsvfile:
        reader = csv.DictReader(tsvfile, delimiter="\t")
        for row in reader:
            grapheme = row.pop("GRAPHEME")
            matrix[grapheme] = {gr: float(dist) for gr, dist in row.items()}

    return matrix