# Backward window #
import dataiku

from clv_forecast.constants import (
    RFM_KEEP_COLUMNS,
    backward_window_columns_rename,
    backward_window_aggregation,
)
from dku_utils.projects.project_commons import get_current_project_and_variables
from dku_utils.projects.recipes.recipe_commons import (
    get_recipe_settings_and_dictionary,
    update_recipe_ouput_schema,
)
from dku_utils.projects.recipes.window_recipe import define_window_recipe_aggregations


def backward_window_features():
    project, variables = get_current_project_and_variables()
    monthly_backward_recipe_name = "compute_monthly_granularity_windows"

    if variables["standard"]["leverage_rfm_segmentation_app"]:
        rfm_dataset = dataiku.Dataset(
            variables["standard"]["rfm_dataset_app"]
        )
        schema = rfm_dataset.read_schema()
        columns = list(
            filter(
                lambda name: (name != "customer_id") and (name != "rfm_reference_date"),
                map(lambda pair: pair["name"], schema),
            )
        )
        for column in columns:
            backward_window_aggregation[column] = ["last"]
            backward_window_columns_rename[f"{column}_last"] = column

    if variables["standard"]["leverage_customer_metadata_app"]:
        rfm_dataset = dataiku.Dataset(
            variables["standard"]["customer_metadata_dataset_app"]
        )

        schema = rfm_dataset.read_schema()
        columns = list(
            filter(
                lambda name: name != "customer_id",
                map(lambda pair: pair["name"], schema),
            )
        )
        for column in columns:
            backward_window_aggregation[column] = ["last"]
            backward_window_columns_rename[f"{column}_last"] = column

    define_window_recipe_aggregations(
        project, monthly_backward_recipe_name, backward_window_aggregation
    )

    recipe_settings, _ = get_recipe_settings_and_dictionary(
        project, monthly_backward_recipe_name, False
    )

    recipe_payload = recipe_settings.get_json_payload()

    recipe_payload["windows"][0]["followingRows"] = -1
    recipe_payload["windows"][0]["precedingRows"] = int(
        variables["standard"]["sliding_lookback_window_app"]
    )
    recipe_payload["outputColumnNameOverrides"] = backward_window_columns_rename

    recipe_settings.set_json_payload(recipe_payload)
    recipe_settings.save()
    update_recipe_ouput_schema(project, monthly_backward_recipe_name)
