import dataiku

from clv_forecast.constants import monthly_full_forward_columns
from dku_utils.projects.project_commons import get_current_project_and_variables
from dku_utils.projects.recipes.join_recipe import programmaticJoinHandler
from dku_utils.projects.recipes.recipe_commons import update_recipe_ouput_schema


def monthly_aggregation():
    project, variables = get_current_project_and_variables()
    recipe_name = "compute_aggregated_monthly_data"

    monthly_backward_dataset = dataiku.Dataset("monthly_windows_prepared")

    schema = monthly_backward_dataset.read_schema()
    columns = list(map(lambda pair: pair["name"], schema))

    join_handler = programmaticJoinHandler(
        project=project,
        recipe_name=recipe_name,
        main_dataset_name="monthly_windows_prepared",
        main_dataset_columns_to_select=columns,
        main_dataset_columns_to_select_alias={},
        main_dataset_computed_columns=[],
    )

    join_handler.add_one_join_on_main_dataset(
        dataset_to_join_name="monthly_forward_value_prepared",
        dataset_to_join_columns_to_select=[
            "forward_window_count",
            "clv_forward_increase",
            "future_average_monthly_value",
        ],
        join_type="LEFT",
        columns_prefix="",
        left_join_key=["ref_date", "customer_id"],
        right_join_key=["ref_date", "customer_id"],
        columns_to_select_alias={},
        dataset_computed_columns=[],
    )
    join_handler.add_one_join_on_main_dataset(
        dataset_to_join_name="average_clv_increase",
        dataset_to_join_columns_to_select=["average_clv_increase"],
        join_type="LEFT",
        columns_prefix="",
        left_join_key=["ref_date"],
        right_join_key=["ref_date"],
        columns_to_select_alias={},
        dataset_computed_columns=[],
    )

    join_handler.add_one_join_on_main_dataset(
        dataset_to_join_name="monthly_granularity_full_backward",
        dataset_to_join_columns_to_select=monthly_full_forward_columns,
        join_type="LEFT",
        columns_prefix="",
        left_join_key=["ref_date", "customer_id"],
        right_join_key=["ref_date", "customer_id"],
        columns_to_select_alias={},
        dataset_computed_columns=[],
    )

    update_recipe_ouput_schema(project, recipe_name)
