# -*- coding: utf-8 -*-
from yt.wrapper import ypath_join
from datacloud.dev_utils.yt import yt_utils
from datacloud.money.yt_helpers import filter_fast_logs, fast_logs_format_mapper
from datacloud.money.pipeline_helpers import formated_logs_to_money, post_money, DAYS_TO_POST

TMP_FOLDER = '//tmp/fast_logs'
FAST_LOGS_YT_HISTORY_FOLDER = '//home/x-products/production/services/logs/datacloud_score_api/fast_logs/clean/history'
MONEY_TAG = 'MONEY_FAST_LOGS'


def calculate_fast_logs_money(yt_client, tag=MONEY_TAG, days_to_post=DAYS_TO_POST):
    with yt_client.Transaction():
        yt_utils.create_folders([TMP_FOLDER], yt_client)

        filtered_fast_logs = ypath_join(TMP_FOLDER, 'filtered_fast_logs')
        fast_logs_list = yt_client.list(FAST_LOGS_YT_HISTORY_FOLDER, absolute=True)
        assert len(fast_logs_list) > 0
        fast_logs_schema = yt_client.get_attribute(fast_logs_list[0], 'schema')

        yt_client.run_map_reduce(
            None,
            filter_fast_logs,
            fast_logs_list,
            yt_client.TablePath(filtered_fast_logs, schema=fast_logs_schema),
            reduce_by='blnsr_req_id',
            spec={'title': '[{}] Filter fast logs'.format(tag)}
        )

        formated_fast_logs = ypath_join(TMP_FOLDER, 'formated_fast_logs')
        yt_client.run_map(
            fast_logs_format_mapper,
            filtered_fast_logs,
            formated_fast_logs,
            spec={'title': '[{}] Format fast logs'.format(tag)}
        )

        money_table = ypath_join(TMP_FOLDER, 'money_table')
        formated_logs_to_money(
            yt_client=yt_client,
            formated_logs=formated_fast_logs,
            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='fast_logs',
            days_to_post=days_to_post
        )
