import re
from functools import partial
from yt.wrapper import ypath_join, ypath_split
from datacloud.dev_utils.time.patterns import RE_DAILY_LOG_FORMAT
from datacloud.config.yt import MODELS_FOLDER

PURE_SCORE_TYPE = 'pure'
BLENDED_SCORE_TYPE = 'blended'
BLENDS_FOLDER_NAME = 'blends'
BLENDS_TO_SAVE = 2

ALL_SCORE_TYPES = set((PURE_SCORE_TYPE, BLENDED_SCORE_TYPE))


def check_node_is_score_table(node, yt_client):
    if not re.match(RE_DAILY_LOG_FORMAT, ypath_split(node)[-1]):
        return False
    if not yt_client.get_attribute(node, 'type') == 'table':
        return False

    return True


def get_all_score_tables(yt_client, partner_id, score_name):
    score_folder = ypath_join(MODELS_FOLDER, partner_id, score_name)
    assert yt_client.exists(score_folder)
    score_folder_nodes = yt_client.list(score_folder, absolute=True)
    return sorted(filter(
        partial(check_node_is_score_table, yt_client=yt_client),
        score_folder_nodes
    ))


def get_all_blended_score_tables(yt_client, partner_id, score_name):
    blended_score_folder = ypath_join(
        MODELS_FOLDER, partner_id, score_name, BLENDS_FOLDER_NAME)
    assert yt_client.exists(blended_score_folder)
    blended_score_nodes = yt_client.list(blended_score_folder, absolute=True)
    return sorted(filter(
        partial(check_node_is_score_table, yt_client=yt_client),
        blended_score_nodes
    ))
