import datetime

import dataiku
from dateutil import relativedelta

from dku_utils.projects.project_commons import get_current_project_and_variables


def update_variables():
    project, variables = get_current_project_and_variables()

    local_variables = variables["local"]
    local_variable_names = local_variables.keys()

    for local_variable_name in local_variable_names:
        local_variable_value = local_variables[local_variable_name]
        global_variable_name = f"{local_variable_name}_app"
        variables["standard"][global_variable_name] = local_variable_value

    if variables["standard"]["custom_max_date_app"]:
        max_year = variables["standard"]["max_year_app"]
        max_month = variables["standard"]["max_month_app"]
        date = f"{max_year}-{max_month}-01T00:00:00.000Z"

        variables["standard"]["max_date_app"] = date
    elif not variables["standard"]["not_connected_flag"]:
        try:
            transactions = dataiku.Dataset("transactions_history")
            metrics = dataiku.core.metrics.ComputedMetrics(
                transactions.get_last_metric_values().raw
            ).get_metric_by_id("col_stats:MAX:transaction_date")
            date = metrics["lastValues"][0]["value"].split("T")[0]
            dt = datetime.datetime.strptime(date, "%Y-%m-%d")

            dt_new = dt + relativedelta.relativedelta(months=1, day=1)
            base_max_date = dt_new.isoformat() + ".000Z"
            variables["standard"]["max_date_app"] = base_max_date
        except:
            pass

    project.set_variables(variables)
