# -*- coding: utf-8 -*-
# Copyright (c) Hebes Intelligence Private Company

# This source code is licensed under the Apache License, Version 2.0 found in the
# LICENSE file in the root directory of this source tree.

import logging

import pandas as pd

from eensight.methods.prediction.metrics import cvrmse, nmbe

logger = logging.getLogger("eensight")


def evaluate_on_test(labels: pd.DataFrame, prediction: pd.DataFrame):
    """Evaluate predictions on `test` data.

    Args:
        labels (pd.DataFrame): The target data.
        prediction (pd.DataFrame): The prediction data.

    Returns:
        dict: The out-of-sample CV(RMSE) and NMBE metrics.
    """

    metrics = {
        "CVRMSE": cvrmse(labels, prediction),
        "NMBE": nmbe(labels, prediction),
    }
    logger.info(f"Out-of-sample metrics: {metrics}")
    return metrics


def evaluate_on_test_autoenc(
    labels: pd.DataFrame,
    prediction: pd.DataFrame,
    activity: pd.DataFrame,
    assume_hurdle: bool,
):
    """Evaluate predictions on `test` data.

    Args:
        labels (pd.DataFrame): The target data.
        prediction (pd.DataFrame): The prediction data.
        activity (pd.DataFrame): The estimated activity levels.
        assume_hurdle (bool): If True, activity estimation will assume that energy
            consumption has been generated by a hurdle model.

    Returns:
        dict: The out-of-sample CV(RMSE) and NMBE metrics.
    """
    if assume_hurdle:
        selected = activity["activity"] == 1
        labels = labels[selected]
        prediction = prediction[selected]

    metrics = evaluate_on_test(labels, prediction)
    return metrics


def evaluate_on_apply(labels: pd.DataFrame, prediction: pd.DataFrame):
    """Evaluate predictions on `apply` data.

    Args:
        labels (pd.DataFrame): The target data.
        prediction (pd.DataFrame): The prediction data.

    Returns:
        pandas.Series: The estimated impact.
    """

    impact = prediction - labels
    return impact


def evaluate_on_apply_autoenc(
    labels: pd.DataFrame,
    prediction: pd.DataFrame,
    activity: pd.DataFrame,
    assume_hurdle: bool,
):
    """Evaluate predictions on `apply` data.

    Args:
        labels (pd.DataFrame): The target data.
        prediction (pd.DataFrame): The prediction data.
        activity (pd.DataFrame): The estimated activity levels.
        assume_hurdle (bool): If True, activity estimation will assume that energy
            consumption has been generated by a hurdle model.

    Returns:
        pandas.Series: The estimated impact.
    """
    impact = prediction - labels
    if assume_hurdle:
        impact = impact["consumption"].mul(activity["activity"]).to_frame("consumption")

    return impact
