# coding=utf-8
from __future__ import unicode_literals, absolute_import, print_function

import traceback

from rpc.decorators import bind
from rpc.context import get_current_context_or_throw_exception

from api.tool.smart_rank import service_rerank, get_smart_rank_detail, cal_expect_cpc
from rpc.tool.log_tool import smart_rank_logger
from rpc.all import get_rpc_remote_invoker


@bind("api/smartrank/rerank")
def smart_rerank(service_ids):
    service_rerank(service_ids)
    ctx = get_current_context_or_throw_exception()
    ctx.logger.app(service_ids=service_ids)

@bind('api/smartrank/pre_cpc')
def pre_cpc_price(service_id):
    '''
    根据美购id, 获取当前美购的cpc单价推荐
    '''
    url = 'doris/search/meigou_cpc_position'
    rpc_invoker = get_rpc_remote_invoker()
    try:
        result = rpc_invoker[url](service_id=service_id).unwrap()
        # result = {'score_list': [{'seq':1, 'score': 100}], 'cur_info': {'score':13, 'seq': 15}}
        cur_info = result.get('cur_info') or {}
        cur_info['detail_info'] = get_smart_rank_detail(service_id)
        score_info_list = result.get('score_list') or []
        cal_expect_cpc(score_info_list, cur_info)
        return result

    except Exception as e:
        smart_rank_logger.error(traceback.format_exc())
        return {}
