from typing import Tuple
from typing import Dict


def fetch_histograms(cursor, table_name: str, attribute_name: str) -> Tuple[int, int, Dict[str, float], int]:
    """Download PostgreSQL histograms from a given table and attribute.

    Args:
      * cursor: A psycopg cursor.
      * table_name: Name of the SQL table from which we should retrieve histograms.
      * attribute_name: Table attribute from which we should retrieve histograms.
    
    Returns:
      A tuple (`null_frac`, `n_distinct`, `selectivities`, `sum_most_common_freqs`) where:
      * `null_frac` is the fraction of null values in the histogram.
      * `n_distinct` is the estimated number of distinct values for this attribute.
      * `selectivities` is the estimated selectivities of the attribute's values in the table.
      * `sum_most_common_freqs` is the num of the frequencies of the most common values for this attribute.
    """
    base_query = f"SELECT null_frac, n_distinct, most_common_vals, most_common_freqs FROM pg_stats WHERE tablename = '{table_name}' AND attname = '{attribute_name}'"
    cursor.execute(base_query)
    record = cursor.fetchone()
    null_frac, n_distinct, most_common_vals, most_common_freqs = record
    # build selectivity table
    selectivities = {}
    cpt = 0
    for common_val in most_common_vals[1:-1].split(","):
        if cpt < len(most_common_freqs):
            selectivities[common_val] = most_common_freqs[cpt]
        cpt += 1
    return (null_frac, n_distinct, selectivities, sum(most_common_freqs))