# -*- coding: utf-8 -*-
from datetime import datetime, timedelta
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.phone_range.phone_range_features import build_phone_range_vectors
from datacloud.features.phone_range.build_config import PhoneRangeBuildConfig
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 detect_ready_phone_range_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_phone_range_features(task):
    yt_client = get_yt_client()
    yql_client = yql_helpers.create_yql_client(yt_client, token=yql_helpers.get_yql_token())
    date_str = task.data['date_str']
    assert_date_str(date_str)

    config = PhoneRangeBuildConfig(is_retro=False, snapshot_date=date_str)
    logger.info(' Start calc phone range for %s', date_str)
    build_phone_range_vectors(yt_client=yt_client, yql_client=yql_client, build_config=config, logger=logger)
    logger.info(' Finish calc phone range for %s', date_str)
    return [task.make_done()]
