# -*- coding: utf-8 -*-
from yt.wrapper import ypath_join
from datacloud.dev_utils.yql.yql_helpers import execute_yql
from datacloud.money.yt_helpers import requests_mapper, join_req_resp
from datacloud.money.pipeline_helpers import formated_logs_to_money, post_money, DAYS_TO_POST

TMP_FOLDER = '//tmp'
RESPONSES = '//home/x-products/production/services/logs/datacloud_score_api/production/responses'
SCORE_API_EVENTS = '//home/x-products/production/partners_data/score_api_audience/logs_formated'
MONEY_TAG = 'MONEY'


def calculate_money(yt_client, tag=MONEY_TAG, days_to_post=DAYS_TO_POST):
    with yt_client.Transaction():
        events_with_id_value = ypath_join(TMP_FOLDER, 'events_with_id_value')
        yt_client.run_map(requests_mapper, SCORE_API_EVENTS, events_with_id_value,
                          spec={'title': '[{}] Map id valus in one'.format(tag)})

        reqs_resps_joined = ypath_join(TMP_FOLDER, 'reqs_resps_joined')
        execute_yql(join_req_resp.format(
            requests_table=events_with_id_value,
            responses_table=RESPONSES,
            result_table=reqs_resps_joined
        ), yt_client=yt_client, syntax_version=1)

        money_table = ypath_join(TMP_FOLDER, 'money_table')
        formated_logs_to_money(
            yt_client=yt_client,
            formated_logs=reqs_resps_joined,
            money_table=money_table,
            tmp_dir=TMP_FOLDER,
            tag=tag
        )

        post_money(
            yt_client=yt_client,
            money_table=money_table,
            tmp_dir=TMP_FOLDER,
            log_type='qloud_logs',
            days_to_post=days_to_post
        )
