from pathlib import Path


def generate_csv(
    symmetric_corr_table, rna_info, data_load_sources, stringency, out_dir
):
    """
    Given a correlation table of RBPs binding to an RNA molecule of interest,
    generates and saves a CSV file containing the correlation values.
    :param symmetric_corr_table: A nested dictionary such that
        symmetric_corr_table[rbp1][rbp2] returns the binding correlation value
        between rbp1 and rbp2.
    :param rna_info: A dictionary containing 'official_name' as key, with a
        corresponding value that indicates the name of the RNA under
        investigation.
    :param data_load_sources: A list of data sources that were used, such as
        'postar', 'rbpdb', etc.
    :param stringency: numerical value representing the base stingency that was
        used in analyzing the correlation coefficient.
    :returns: a filepath to the saved CSV file.

    """
    rna = rna_info["official_name"]

    path_to_save = (
        Path(out_dir)
        / "csv"
        / f"{rna.lower()}-{'-'.join(data_load_sources)}-{stringency}.csv"
    )

    path_to_save.parent.mkdir(parents=True, exist_ok=True)
    path_to_save = str(path_to_save)

    with open(path_to_save, "w+") as csv_file:
        rbps = list(symmetric_corr_table.keys())
        csv_file.write("," + ",".join(rbps))
        csv_file.write("\n")
        for rbp1 in rbps:
            csv_file.write(rbp1 + ",")
            for rbp2 in rbps:
                csv_file.write(str(symmetric_corr_table[rbp1][rbp2]))
                csv_file.write(",")
            csv_file.write("\n")

    return path_to_save