# -*- coding: utf-8 -*-
import os
import yt.wrapper as yt_wrapper
from datetime import datetime, timedelta
from yt.wrapper import ypath_join

from datacloud.dev_utils.logging.logger import get_basic_logger
from datacloud.dev_utils.yt.yt_utils import get_yt_client
from datacloud.dev_utils.time.patterns import FMT_DATE_HM, FMT_DATE
from datacloud.features.contact_actions.build_config import CONTACT_LOG_DIR
from datacloud.features.contact_actions.contact_actions_grep import run_grep
from datacloud.features.contact_actions.build_config import ContacActionsBuildConfig
from datacloud.features.contact_actions.contact_actions_features import build_contac_actions_vectors
from datacloud.dev_utils.crypta import crypta_snapshot
from datacloud.dev_utils.yql import yql_helpers
from datacloud.dev_utils.time.utils import assert_date_str


logger = get_basic_logger()


def get_yql_token():
    yql_token = os.environ.get('YQL_TOKEN')
    if not yql_token:
        yql_token = yt_wrapper.config['token']
    assert yql_token, 'Please provide YQL token'

    return yql_token


def detect_ready_contact_actions_grep(date_time):
    yt_client = get_yt_client()
    date_time = datetime.strptime(date_time, FMT_DATE_HM)

    if date_time.weekday() != 0:  # Run only on monday
        logger.info(' Skip %s, not monday', date_time)
        return

    week_start = (date_time - timedelta(days=7)).strftime(FMT_DATE)
    week_end = (date_time - timedelta(days=1)).strftime(FMT_DATE)

    result_table = ypath_join(CONTACT_LOG_DIR, week_end)
    if yt_client.exists(result_table):
        logger.info(' Already calculated %s', result_table)
        return

    yield week_end, {'date_from': week_start, 'date_to': week_end}


def run_contact_actions_grep(task):
    yt_client = get_yt_client()

    date_from = task.data['date_from']
    date_to = task.data['date_to']

    assert_date_str(date_from)
    assert_date_str(date_to)

    logger.info(' Start grep contact actions for range [%s, %s]', date_from, date_to)
    run_grep(date_from, date_to, yt_client=yt_client)
    logger.info(' Finish grep contact actions for range [%s, %s]', date_from, date_to)
    return [task.make_done()]


def detect_ready_contact_actions_features(date_time, days=None):
    yt_client = get_yt_client()
    days = days or 5
    date_time = datetime.strptime(date_time, FMT_DATE_HM)
    for min_diff in xrange(days):
        time_to_check = date_time - timedelta(days=min_diff)
        logger.info(' Check day: {}'.format(time_to_check))
        date_str = time_to_check.strftime(FMT_DATE)
        snapshot = crypta_snapshot.get_snapshot(yt_client, date_str)
        if snapshot is not None:
            yield date_str, {'date_str': date_str}
            break


def run_contact_actions_features(task):
    yt_client = get_yt_client()
    yql_client = yql_helpers.create_yql_client(yt_client, token=get_yql_token())
    date_str = task.data['date_str']

    assert_date_str(date_str)

    snapshot = crypta_snapshot.get_snapshot(yt_client, date_str)
    config = ContacActionsBuildConfig(
        root=None,
        is_retro=False,
        snapshot_date=date_str,
        email_id_value_to_cid=snapshot.email_id_value_to_cid,
        phone_id_value_to_cid=snapshot.phone_id_value_to_cid,
    )
    logger.info(' Start calc contact actions for %s', date_str)
    build_contac_actions_vectors(yt_client=yt_client, yql_client=yql_client, build_config=config, logger=None)
    logger.info(' Finish calc contact actions for %s', date_str)
    return [task.make_done()]
