import os
import sys

sys.path.append(os.path.dirname(sys.path[0]))  # 上级目录

from utils.DolphinschedulerHelper import DolphinschedulerHelper
from utils.redis_utils import RedisUtils

from utils.common_util import CommonUtil

if __name__ == '__main__':
    # 监听半小时之内报错的任务
    client = RedisUtils.getClient()
    redis_key = "dolphinscheduler_task_monitor:lateTime"
    lateTime = client.get(redis_key)
    lateTime = lateTime or "2026-03-20 00:00:00"
    import json

    print(lateTime)

    req_params = {
        "pageNo": 1,
        "pageSize": 100,
        "stateType": "FAILURE",
        "startDate": lateTime
    }
    project_name = "big_data_selection"
    errList = DolphinschedulerHelper.list_projects_task(project_name=project_name, req_params=req_params)

    errMsg = []
    for it in errList:
        task_name = "-".join(it['name'].split("-")[:-2])
        paramMap = DolphinschedulerHelper.view_process_instance_variables(project_name, it["id"])
        errMsg.append(f"""任务[{task_name}]执行失败,启动参数为:{json.dumps(paramMap)}""")

    from datetime import datetime

    now = datetime.now()
    formatted_time = now.strftime("%Y-%m-%d %H:%M:%S")

    if len(errMsg) > 0:
        all_msg = "\n".join(errMsg)
        msg = f"""截止到日期{lateTime}到{formatted_time},海豚任务报错详情如下\n{all_msg}"""
        CommonUtil.send_msg_robot(msg)

    client.set(redis_key, formatted_time)
