# -*- coding: utf-8 -*-
import argparse
import json

import pytz
import requests

from datetime import datetime

server_robot = {
    'webhook': 'https://open.feishu.cn/open-apis/bot/v2/hook/926982f5-e7af-40f5-81fd-27d8f42718e4',
}

level_header_template_map = {
    "info": "turquoise",
    "error": "red",
    "warn": "yellow"
}

level_header_title_content_map = {
    "info": "广告模型自动更新通知",
    "error": "广告模型自动更新告警",
    "warn": "广告模型自动更新告警"
}

level_task_status_map = {
    "info": "任务执行成功",
    "error": "任务执行失败",
    "warn": "任务执行失败",
}


def send_card_msg_to_feishu(webhook, card_json):
    """发送消息到飞书"""
    headers = {'Content-Type': 'application/json'}
    payload_message = {
        "msg_type": "interactive",
        "card": card_json
    }
    print(f"推送飞书消息内容: {json.dumps(payload_message)}")
    response = requests.request('POST', url=webhook, headers=headers, data=json.dumps(payload_message))
    print(response.text)


def timestamp_format(timestamp: str) -> str:
    try:
        return (datetime.utcfromtimestamp(int(timestamp))
                .replace(tzinfo=pytz.UTC)
                .astimezone(pytz.timezone('Asia/Shanghai'))
                .strftime('%Y-%m-%d %H:%M:%S')
                )
    except ValueError as e:
        return timestamp


def seconds_convert(seconds):
    hours = seconds // 3600
    minutes = (seconds % 3600) // 60
    seconds = seconds % 60
    return f"{hours}小时 {minutes}分钟 {seconds}秒"


def _monitor(level, msg: str, start, elapsed, top10):
    """消息推送"""
    """消息推送"""
    now = datetime.now()
    msg = msg.replace("\\n", "\n").replace("\\t", "\t")
    mgs_text = f"- 当前时间: {now.strftime('%Y-%m-%d %H:%M:%S')}" \
               f"\n- 任务开始时间: {timestamp_format(start)}" \
               f"\n- 任务状态: {level_task_status_map[level]}" \
               f"\n- 任务耗时: {seconds_convert(elapsed)}" \
               f"\n- 任务描述:\n{msg}"
    card_json = {
        "schema": "2.0",
        "header": {
            "title": {
                "tag": "plain_text",
                "content": level_header_title_content_map[level]
            },
            "template": level_header_template_map[level]
        },
        "body": {
            "elements": [
                {
                    "tag": "markdown",
                    "content": mgs_text,
                    "text_align": "left",
                    "text_size": "normal",
                    "element_id": "overview"
                }
            ]
        }
    }
    if top10 is not None and len(top10) > 0:
        collapsible_panel = {
            "tag": "collapsible_panel",
            "header": {
                "title": {
                    "tag": "markdown",
                    "content": "**Top10差异详情**"
                },
                "vertical_align": "center",
                "padding": "4px 0px 4px 8px"
            },
            "border": {
                "color": "grey",
                "corner_radius": "5px"
            },
            "element_id": "detail",
            "elements": [
                {
                    "tag": "markdown",
                    "content": top10.replace("\\n", "\n").replace("\\t", "\t"),
                    "element_id": "Top10CID"
                }
            ]
        }
        card_json['body']['elements'].append(collapsible_panel)

    send_card_msg_to_feishu(
        webhook=server_robot.get('webhook'),
        card_json=card_json
    )


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='告警Utils')
    parser.add_argument('--level', type=str, help='通知级别, info, warn, error', required=True)
    parser.add_argument('--msg', type=str, help='消息', required=True)
    parser.add_argument('--start', type=str, help='任务开始时间', required=True)
    parser.add_argument('--elapsed', type=int, help='任务耗时【秒】', required=True)
    parser.add_argument("--top10", type=str, help='Top10打分详情', required=False)
    args = parser.parse_args()

    _monitor(
        level=args.level,
        msg=args.msg,
        start=args.start,
        elapsed=args.elapsed,
        top10=args.top10
    )
