# -*- coding: utf-8 -*-
import json
import vh
from datacloud.dev_utils.logging.logger import get_nirvana_logger

logger = get_nirvana_logger(__name__)


@vh.lazy.hardware_params(vh.HardwareParams(max_ram=1024))
@vh.lazy(
    object,
    gs_results=vh.mkinput(vh.File, nargs='*'),
    useragent=vh.mkoption(str, default=''),
    st_token=vh.mkoption(vh.Secret),
    ticket_name=vh.mkoption(str),
    comment_id=vh.mkoption(str, default=''),
    features_tag=vh.mkoption(str, default=''),
    ST_Logger_cls=object
)
def process_gs_results(gs_results, useragent, st_token, ticket_name,
                       comment_id, features_tag, ST_Logger_cls):
    logger.info('Began processing gs resutls')

    results_formatted = {}
    for result in gs_results:
        with open(result) as f:
            data = json.load(f)
            results_formatted[data['target_name']] = data

    st_logger = ST_Logger_cls(token=st_token.value, ticket_name=ticket_name,
                              useragent=useragent, comment_id=comment_id)
    st_logger.write_train_results(results=results_formatted, features_tag=features_tag)
    st_logger.push()

    logger.info(results_formatted)


@vh.module(
    out=vh.mkoutput(vh.File),
    params=vh.mkoption(str),
    ticket_name=vh.mkoption(str),
    target_name=vh.mkoption(str, default=''),
    features_tag=vh.mkoption(str, default=''),
    max_ram=vh.mkoption(int, default=64 * 1024),
    ttl=vh.mkoption(int, default=72 * 3600),
    cpu_guarantee=vh.mkoption(int, default=800)
)
def run_grid_search(out, params, ticket_name, target_name, features_tag,
                    max_ram, ttl, cpu_guarantee):
    option2json_op = vh.op(name='Single Option To Json Output', owner='robot-hitman')
    option2json = option2json_op(
        input=params, _name='{} / {} / {}'.format(ticket_name, features_tag, target_name)
    )

    executable = vh.arcadia_executable('datacloud/ml_utils/grid_search_wrapper/nirvana_cube')
    yt_token_secret = vh.get_yt_token_secret()
    vh.tgt(out, executable, option2json, yt_token_secret,
           recipe='YT_TOKEN={{ yt_token_secret }} {{ executable }} {{ option2json }} {{ OUT }}',
           hardware_params=vh.HardwareParams(max_ram=max_ram, ttl=ttl, cpu_guarantee=cpu_guarantee))
