"""
@author: luojunhui
"""
import requests
import traceback

from applications import bot
from applications.decoratorApi import retryOnTimeout

BALANCE_LIMIT_THRESHOLD = 200.0


@retryOnTimeout(retries=5, delay=5)
def check_kimi_balance():
    """
    校验kimi余额
    :return:
    """
    url = "https://api.moonshot.cn/v1/users/me/balance"

    payload = {}
    headers = {
        'Authorization': 'Bearer sk-5DqYCa88kche6nwIWjLE1p4oMm8nXrR9kQMKbBolNAWERu7q'
    }
    response = requests.request("GET", url, headers=headers, data=payload, timeout=10)
    if response.status_code == 200:
        response_json = response.json()
        try:
            balance = response_json['data']['available_balance']
            if balance < BALANCE_LIMIT_THRESHOLD:
                bot(
                    title="kimi余额小于 {} 块".format(BALANCE_LIMIT_THRESHOLD),
                    detail={
                        "balance": balance
                    }
                )
        except Exception as e:
            error_stack = traceback.format_exc()
            bot(
                title="kimi余额接口处理失败，数据结构异常",
                detail={
                    "error": str(e),
                    "error_msg": error_stack
                }
            )
    else:
        bot(
            title="kimi余额接口调用失败",
            detail={
                "response": response.text
            }
        )


if __name__ == '__main__':
    check_kimi_balance()
