import dataiku

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 (
    adapt_recipe_engine_to_priority_and_availability,
    update_recipe_ouput_schema,
)
from markdown_optimization.constants import CONFIGURATION_DATA_SCHEMA


def join_features_for_history():
    project, variables = get_current_project_and_variables()
    recipe_name = "compute_demand_forecast_features_on_scope"

    optional_datasets = variables["standard"]["optional_datasets_app"]

    selected_datasets = set(optional_datasets).intersection(
        CONFIGURATION_DATA_SCHEMA.keys()
    )

    features_dataset = dataiku.Dataset("demand_forecast_data_prepared")
    schema_features = features_dataset.read_schema()
    features_columns = list(map(lambda pair: pair["name"], schema_features),)

    configuration_dataset = dataiku.Dataset("product_strategy_synced")
    schema_config = configuration_dataset.read_schema()
    configuration_columns = list(map(lambda pair: pair["name"], schema_config),)
    configuration_columns.remove("product_id")

    join_handler = programmaticJoinHandler(
        project=project,
        recipe_name=recipe_name,
        main_dataset_name="demand_forecast_data_prepared",
        main_dataset_columns_to_select=features_columns,
        main_dataset_columns_to_select_alias={},
        main_dataset_computed_columns=[],
    )
    join_handler.add_one_join_on_main_dataset(
        dataset_to_join_name="product_strategy_synced",
        dataset_to_join_columns_to_select=configuration_columns,
        join_type="LEFT",
        columns_prefix=None,
        left_join_key=["product_id"],
        right_join_key=["product_id"],
        columns_to_select_alias={},
        dataset_computed_columns=None,
    )

    if "product_inventory" in selected_datasets:
        join_handler.add_one_join_on_main_dataset(
            dataset_to_join_name="product_inventory",
            dataset_to_join_columns_to_select=["stock"],
            join_type="LEFT",
            columns_prefix=None,
            left_join_key=["product_id", "forecast_granularity"],
            right_join_key=["product_id", "forecast_granularity"],
            columns_to_select_alias={},
            dataset_computed_columns=None,
        )

    adapt_recipe_engine_to_priority_and_availability(project, recipe_name)
    update_recipe_ouput_schema(project, recipe_name)

    output_dataset = "demand_forecast_features_on_scope"
    join_output_dataset = project.get_dataset(output_dataset)
    join_output_dataset.build()
