# -*- coding: utf-8 -*-
from datacloud.dev_utils.logging.logger import get_basic_logger
from datacloud.dev_utils.yt.yt_utils import get_yt_client
from datacloud.stability.crypta_stability import (
    api_stable, cids_stable, id_value_stable
)
from datacloud.stability.crypta_stability.constants import (
    CRYPTA_DB_Q, CRYPTA_DB_LAST
)

logger = get_basic_logger(__name__)


def release_crypta(yt_client, crypta_quarantine=CRYPTA_DB_Q, crypta_last=CRYPTA_DB_LAST):
    with yt_client.Transaction():
        yt_client.copy(crypta_quarantine, crypta_last, recursive=True, force=True)
        for table in yt_client.list(crypta_quarantine, absolute=True):
            yt_client.remove(table, force=True)


def check_crypta_stability(task):
    logger.info('Begin checking crypta stability')
    yt_client = get_yt_client()
    stable = api_stable.check_api_stable(yt_client)
    cids_stable.check_cids_stability(yt_client)
    id_value_stable.check_id_value_stability(yt_client)

    logger.info('Crypta stability checks completed')

    release_crypta(yt_client)
    if stable:
        logger.info('Crypta is table')
    else:
        logger.info('Crypta is unstable')

    return [task.make_done()]
