from typing import Dict
from typing import Any
from typing import Optional
from typing import Tuple
from typing import List


def prepare_final_dataset_and_labels(
    data: Dict[str, Any], subreddit_labels: Optional[Dict[str, str]] = None
) -> Tuple[List[Dict], Dict[str, str]]:
    """Prepare dataset and labels for clustering. Determine a 'derived' label from the subreddit_labels.

    Args:
        data: The dataset
        subreddit_labels: Contains the subreddit / label mapping when specified

    Returns:
        final_data: the data in proper format for downstream clustering
        final_derived_labels: contains a mapping between datum id and derived label.
    """
    final_derived_labels = {}
    final_data = []
    for subreddit, subreddit_data in data.items():
        for title in subreddit_data:
            # if we have annotations available, use them to get a more informed label,
            # otherwise use the subreddit as the label
            derived_label = (
                subreddit_labels[subreddit]
                if subreddit_labels is not None
                else subreddit
            )

            # prepare title / label
            final_derived_labels[title["id"]] = derived_label
            final_data.append(
                {
                    "text": title["text"],
                    "id": title["id"],
                    "label": derived_label,
                }
            )
    return final_data, final_derived_labels