import datetime
import json
import traceback

from my_utils import request_get, send_msg_to_feishu
from db_helper import RedisHelper
from my_config import set_config
from log import Log

config_, _ = set_config()
log_ = Log()


def get_ad_ecpm():
    """获取广告ecpm值"""
    ad_ecpm = {}
    result = request_get(request_url=config_.GET_AD_ECPM_URL)
    print(result)
    if result is None:
        log_.info('获取广告ecpm值失败！')
        return ad_ecpm
    if result['code'] != 0:
        log_.info('获取广告ecpm值失败！')
        return ad_ecpm
    if not result['data']:
        return ad_ecpm
    ad_ecpm = result['data']
    print(ad_ecpm)
    return ad_ecpm


def update_ad_ecpm():
    try:
        now_date = datetime.datetime.today()
        log_.info(f"now_date: {datetime.datetime.strftime(now_date, '%Y%m%d%H')}")

        # 获取广告ecpm值
        ad_ecpm = get_ad_ecpm()
        log_.info(f"ad_ecpm: {ad_ecpm}")
        if len(ad_ecpm) == 0:
            send_msg_to_feishu(
                webhook=config_.FEISHU_ROBOT['server_robot'].get('webhook'),
                key_word=config_.FEISHU_ROBOT['server_robot'].get('key_word'),
                msg_text=f"rov-offline{config_.ENV_TEXT} - 广告ecpm获取失败！"
            )
            return
        redis_helper = RedisHelper()
        redis_helper.set_data_to_redis(key_name=config_.KEY_NAME_AD_ECPM, value=json.dumps(ad_ecpm))
        redis_helper.persist_key(key_name=config_.KEY_NAME_AD_ECPM)

        # send_msg_to_feishu(
        #     webhook=config_.FEISHU_ROBOT['server_robot'].get('webhook'),
        #     key_word=config_.FEISHU_ROBOT['server_robot'].get('key_word'),
        #     msg_text=f"rov-offline{config_.ENV_TEXT} - 广告ecpm更新完成！\nad_ecpm = {ad_ecpm}"
        #
        # )
        log_.info(f"ad ecpm update end!")

    except Exception as e:
        log_.error(f"广告ecpm更新失败, exception: {e}, traceback: {traceback.format_exc()}")
        send_msg_to_feishu(
            webhook=config_.FEISHU_ROBOT['server_robot'].get('webhook'),
            key_word=config_.FEISHU_ROBOT['server_robot'].get('key_word'),
            msg_text=f"rov-offline{config_.ENV_TEXT} - 广告ecpm更新失败\n"
                     f"exception: {e}\n"
                     f"traceback: {traceback.format_exc()}"
        )


if __name__ == '__main__':
    update_ad_ecpm()
