from dku_utils.projects.project_commons import get_current_project_and_variables

configuration = {
    "Filesystem": {
        "main_connection_name": "filesystem_managed",
        "folder_connection_name": "filesystem_folders",
        "connection_type": "Filesystem",
        "fallback_connection_name": "blob_storage_dev",
        "max_date": "2011-12-01T00:00:00.000Z",
        "transactions_history_table_name": "RETAIL_AND_CPG_DATALAKE/transaction_history_uci",
        "customer_metadata_table_name": "",
        "customer_rfm_segments_table_name": "",
        "leverage_customer_metadata": False,
        "leverage_rfm_segmentation": False,
        "managed_dataset_format": "csv",
    },
    "Snowflake": {
        "main_connection_name": "managed-snowflake",
        "folder_connection_name": "filesystem_folders",
        "max_date": "2019-12-01T00:00:00.000Z",
        "connection_type": "Snowflake",
        "fallback_connection_name": "blob_storage_dev",
        "transactions_history_table_name": "TRANSACTIONS_HISTORY_space-1953178d-int2_node-f67415e3_RETAIL_AND_CPG_DATALAKE",
        "customer_metadata_table_name": "CUSTOMER_METADATA_space-1953178d-int2_node-f67415e3_RETAIL_AND_CPG_DATALAKE",
        "customer_rfm_segments_table_name": "RFMSEGMENTATIONREALDATA_all_customer_rfm_segments",
        "leverage_customer_metadata": True,
        "leverage_rfm_segmentation": True,
        "managed_dataset_format": "csv",
    },
}


def configuration_test(
    configuration_var,
    connection_update_scenario,
    main_scenario,
    variable_context="local",
):
    project, variables = get_current_project_and_variables()
    variables[variable_context].update(configuration_var)
    project.set_variables(variables)
    print("Running scenario '{}' ...".format(main_scenario))
    outcome_status = {
        "connection_scenario": {
            "id": connection_update_scenario,
            "status": "FAILED",
            "duration": 0.0,
        },
        "main_scenario": {"id": main_scenario, "status": "FAILED", "duration": 0.0},
    }
    # update connections
    scenario = project.get_scenario(connection_update_scenario)
    scenario.run_and_wait(no_fail=True)
    scenario_run = scenario.get_last_finished_run()

    outcome_status["connection_scenario"]["status"] = scenario_run.outcome
    outcome_status["connection_scenario"]["duration"] = scenario_run.get_duration()
    if scenario_run.outcome in ["FAILED", "ABORTED"]:
        # if the connection change fails, don't run the main scenario
        return outcome_status
    else:
        # run scenario
        scenario = project.get_scenario(main_scenario)
        scenario.run_and_wait()
        scenario_run = scenario.get_last_finished_run()
        outcome_status["main_scenario"]["status"] = scenario_run.outcome
        outcome_status["main_scenario"]["duration"] = scenario_run.get_duration()
    return outcome_status
