from yt.wrapper import ypath_join
from datacloud.stability import batch_monitoring
from datacloud.stability.mini_batch_monitoring.perform import perfrom_mini_batch_monitoring
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.status_db.db import lock_manager, LockError
from datacloud.dev_utils.yt import yt_utils
from datacloud.model_applyer.tables.models_config_table import ApiModelsConfigTable

logger = get_basic_logger(__name__)
MINI_BATCH_LOCK_NAME = 'minibatch-lock'


# Detect ready is used the same way as it was done in module 'datacloud_psi_solomon.py'
def run_batch_monitoring(task):
    from datacloud.config.yt import YT_PROXY
    logger.info('[BATCH_MONITORING] Run batch monitoring')
    yt_client = yt_utils.get_yt_client(YT_PROXY)
    score_table = task.data['table_path']
    logger.info('Start upload table: {}'.format(score_table))

    partner_id = task.data['partner_id']
    score_name = task.data['score_name']
    score_date = task.data['score_date']
    score_type = task.data['score_type']
    batch_monitoring.run_calc_auc_hit_workflow(
        yt_client=yt_client, score_table=score_table, partner_id=partner_id,
        score_name=score_name, score_date=score_date, score_type=score_type)
    return [task.make_done()]


def run_mini_batch_monitoring(task):
    yt_client = get_yt_client()
    partner_id = task.data['partner_id']
    score_name = task.data['score_name']
    score_date = task.data['date_str']

    config_rec = ApiModelsConfigTable().get_model(partner_id, score_name)
    assert config_rec is not None, 'Not found config for {partner_id}, {score_name}'.format(
        partner_id=partner_id, score_name=score_name)

    batch_names = [m['batch_name'] for m in config_rec['additional'].get('batch_monitoring', [])]
    batch_tables = [
        ypath_join(batch_monitoring.TEST_SAMPLES_FOLDER, batch_name)
        for batch_name in batch_names
    ]

    try:
        with lock_manager(MINI_BATCH_LOCK_NAME):
            if len(batch_tables) == 0:
                logger.info('No batch monitoring retro tables found!')
            for batch_table in batch_tables:
                logger.info('Start of {partner_id}/{score_name} mini batch '
                            'monitoring by {batch_table}'.format(partner_id=partner_id,
                                                                 score_name=score_name,
                                                                 batch_table=batch_table))
                perfrom_mini_batch_monitoring(
                    yt_client=yt_client, partner_id=partner_id, score_name=score_name,
                    score_date=score_date, batch_table=batch_table)

            return [task.make_done()]
    except LockError:
        logger.error('Mini batch monitoring is locked!')

    return []
