from __future__ import print_function
from yt.wrapper import ypath_split
from datacloud.dev_utils.yt import yt_config_table
from datacloud.dev_utils.logging.logger import get_basic_logger
from datacloud.dev_utils.time.utils import assert_date_str


logger = get_basic_logger(__name__)
DEFAULT_PATH = '//home/x-products/production/config/datacloud/apply-history'


__all__ = [
    'ApplyHistoryTable'
]


class ApplyHistoryTable(yt_config_table.ConfigTable):
    def __init__(self, table_path=DEFAULT_PATH, yt_client=None):
        schema = [
            {'name': 'score_name', 'type': 'string', 'sort_order': 'ascending'},
            {'name': 'date_str', 'type': 'string', 'sort_order': 'ascending'},
            {'name': 'features_dict', 'type': 'any'},
            {'name': 'additional', 'type': 'any'},
        ]
        super(ApplyHistoryTable, self).__init__(
            table_path, schema, yt_client
        )

    def add_record(self, score_name, date_str, features_dict, additional=None):
        assert_date_str(date_str)
        additional = additional or {}

        record = {
            'score_name': score_name,
            'date_str': date_str,
            'features_dict': features_dict,
            'additional': additional
        }
        self.insert_records([record])

    def add_applied_model(self, model_config):
        features_dict = dict()
        for feature in model_config.required_features:
            feature_name = feature.feature_name
            features_dict[feature_name] = [ypath_split(feature.get_last_weekly_table())[-1]]

        self.add_record(
            model_config.score_name,
            model_config.date_str,
            features_dict
        )
