# -*- coding: utf-8 -*-
from datetime import datetime
from yt.wrapper import ypath_join

from datacloud.features.credit_scoring_events.build_config import CSEBuildConfig
from datacloud.features.credit_scoring_events.cse_features import build_vectors
from datacloud.dev_utils.yt.yt_utils import get_yt_client
from datacloud.dev_utils.logging.logger import get_basic_logger
from datacloud.dev_utils.time.patterns import FMT_DATE_HM, FMT_DATE

logger = get_basic_logger()


def detect_ready_cse_features(date_time, days=None):
    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 {}, not monday'.format(date_time))
        return

    date_str = date_time.strftime(FMT_DATE)
    config = CSEBuildConfig(date=date_str)
    if yt_client.exists(config.features_table):
        logger.info(' Already calculated {}'.format(ypath_join(config.data_dir, date_str)))
        return

    yield date_str, {'date_str': date_str}  # config.features_table.to_yson_type().capitalize(), True


def build_cse_features(task):
    yt_client = get_yt_client()
    date_str = task.data['date_str']

    config = CSEBuildConfig(date=date_str)
    logger.info(' Building {}'.format(config.features_table))
    build_vectors(build_config=config, yt_client=yt_client)
    logger.info(' Features built!')

    return [task.make_done()]
