import torch


def rae(target, predictions: list, total=True):
    """
    Calculate the RAE (Relative Absolute Error) compared to a naive forecast that only
    assumes that the future will produce the average of the past observations

    Parameters
    ----------
    target : torch.Tensor
        The true values of the target variable
    predictions : list
        - predictions[0] = y_hat_test, predicted expected values of the target variable (torch.Tensor)
    total : bool, default = True
        Used in other loss functions to specify whether to return overall loss or loss over
        the horizon. This function only supports the former.

    Returns
    -------
    torch.Tensor
        A scalar with the overall RAE (the lower the better)

    Raises
    ------
    NotImplementedError
        When 'total' is set to False, as rae does not support loss over the horizon
    """

    y_hat_test = predictions[0]
    y_hat_naive = torch.mean(target)

    if not total:
        raise NotImplementedError("rae does not support loss over the horizon")

    # denominator is the mean absolute error of the preidicity dependent "naive forecast method"
    # on the test set -->outsample
    return torch.mean(torch.abs(target - y_hat_test)) / torch.mean(torch.abs(target - y_hat_naive))