import math


def _scoring_function(
    highlight,
    original_position,
    adversarial_position,
    original_confidence,
    adversarial_confidence,
    start_idx,
    end_idx,
):
    """
    scoring function for highlighting of the interval start_idx:end_idx
    :param highlight: np.array of shape (n_tokens)
    :param original_position: ranking position of the target intent for the original sentence
    :param adversarial_position: ranking position of the target intent for the adversarial sentence
    :param original_confidence: confidence of the target intent for the original sentence
    :param adversarial_confidence: confidence of the target intent for the adversarial sentence
    :param start_idx: starting index of the adversarial mask
    :param end_idx: ending index of the adversarial mask
    :return: highlight: np.array of shape (n_tokens)
    """
    # position difference accounts for the change in the position of the target intent among
    # the top 10 intents return by the message api
    position_difference = (1 / float(original_position + 1.0)) - (
        1 / float(adversarial_position + 1.0)
    )

    # confidence difference accounts for the change in the confidence
    confidence_difference = original_confidence - adversarial_confidence

    ngram_size = end_idx - start_idx
    weight = math.pow(1.0 / ngram_size, 2.0)

    # highlight score for the interval of start_idx:end_idx is a weighted average of
    # the position difference and confidence difference
    weighted_difference = (
        weight
        * ((0.2 * confidence_difference) + (0.8 * position_difference))
        / ngram_size
    )

    highlight[start_idx:end_idx] += weighted_difference

    return highlight