import os
from datetime import datetime
import yt.wrapper as yt_wrapper
from datacloud.config.yt import YT_PROXY
from datacloud.dev_utils.ydb.lib.deploy import (
    recipe, record_storage, deploy_manager)
from datacloud.dev_utils.logging.logger import get_basic_logger
from datacloud.dev_utils.ydb.lib.core.ydb_manager import (
    YdbManager, YdbConnectionParams)
from datacloud.dev_utils.time.patterns import FMT_DATE_HM, FMT_DATE


logger = get_basic_logger(__name__)
BACKUP_YT_PATH = '//projects/scoring/ydb-backup'


def detect_ready_backup_ydb(date_time, days=None):
    yt_wrapper.config.set_proxy(YT_PROXY)
    date_time = datetime.strptime(date_time, FMT_DATE_HM)
    if date_time.weekday() == 0:  # Run only on monday
        date_str = date_time.strftime(FMT_DATE)
        yield date_str, {'date_str': date_str}


def run_backup_ydb(task):
    token = os.environ['YDB_TOKEN']
    db_info = recipe.PROD_CONFIG.db_info
    yt_wrapper.config.set_proxy(db_info.yt_cluster)

    connection_params = YdbConnectionParams(
        endpoint=db_info.ydb_endpoint,
        database=db_info.ydb_database,
        auth_token=token
    )

    manager = YdbManager(connection_params)
    deployer = deploy_manager.Deployer(manager, db_info.ydb_database)
    storage = record_storage.Yt(yt_wrapper, BACKUP_YT_PATH)
    to_backup = (
        recipe.PROD_CONFIG,
        recipe.PROD_GEO,
    )
    with yt_wrapper.Transaction():
        for current_recipe in to_backup:
            _backup_recipe(deployer, storage, current_recipe)
    return [task.make_done()]


def _backup_recipe(deployer, storage, current_recipe):
    logger.info('[BACKUP] Start recipe')
    for harvesting in current_recipe.harvesting_group:
        yt_table = yt_wrapper.ypath_join(BACKUP_YT_PATH, harvesting.rel_path)
        if yt_wrapper.exists(yt_table):
            logger.info('Table {} exists, remove'.format(yt_table))
            yt_wrapper.remove(yt_table)
    deployer.dump(current_recipe, storage)
