from typing import List
from typing import Optional


def equally_weighted_classes(foreground_classes: List[str], background_weight: Optional[float] = None) -> List:
    """
    Computes a list of weights for the background class and all foreground classes. If no background_weight
    is given, all foreground classes and the background class (class index 0) are given equal weight.
    If a background_weight is given explicitly, that weight is assigned to class index 0, and the rest of the weight
    is equally distributed across all foreground classes. All weights will sum to 1.0

    :param foreground_classes: The list of foreground classes that the model uses.
    :param background_weight: The weight that should be given to the background class (index 0). This can be None.
    :return: A list of length len(foreground_classes) + 1, with weights for all classes including the background class.
            The weights will sum to 1.0
    """
    num_foreground_classes = len(foreground_classes)
    if num_foreground_classes == 0:
        raise ValueError("No foreground class present.")
    if background_weight is None:
        num_classes_with_background = num_foreground_classes + 1
        return [1.0 / num_classes_with_background] * num_classes_with_background
    if background_weight < 0.0 or background_weight >= 1.0:
        raise ValueError(f"background_weight must be in the interval [0, 1), but got: {background_weight}")
    foreground_weight = (1.0 - background_weight) / num_foreground_classes
    return [background_weight] + [foreground_weight] * num_foreground_classes