package com.ruoshui.bigdata.core.thread;

import com.ruoshui.bigdata.core.conf.JobAdminConfig;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FeishuUtil {
    private static Logger logger = LoggerFactory.getLogger(FeishuUtil.class);

    public static void send(String alarmContent, String title, String content) {
        String webhookUrl = JobAdminConfig.getAdminConfig().getFeishuWebhookUrl();
        
        if (webhookUrl == null || webhookUrl.trim().isEmpty()) {
            logger.warn(">>>>>>>>>>> ruoshui-ground, feishu webhook url is empty, skip send feishu notification.");
            return;
        }

        try {
            JSONObject card = new JSONObject();
            card.set("config", new JSONObject().set("wide_screen_mode", true));

            JSONObject header = new JSONObject();
            JSONObject titleObj = new JSONObject();
            titleObj.set("tag", "plain_text");
            titleObj.set("content", title);
            header.set("title", titleObj);
            header.set("template", "red");
            card.set("header", header);

            JSONObject element = new JSONObject();
            element.set("tag", "markdown");
            element.set("content", formatMarkdownContent(alarmContent, content));
            card.set("elements", new Object[]{element});

            JSONObject requestBody = new JSONObject();
            requestBody.set("msg_type", "interactive");
            requestBody.set("card", card);

            String result = HttpUtil.post(webhookUrl, requestBody.toString());

            logger.info(">>>>>>>>>>> ruoshui-ground, job fail alarm feishu send result:{}", result);

            JSONObject resultJson = JSONUtil.parseObj(result);
            if (resultJson != null && resultJson.getInt("code") != null && resultJson.getInt("code") == 0) {
                logger.info(">>>>>>>>>>> ruoshui-ground, job fail alarm feishu send success.");
            } else {
                logger.error(">>>>>>>>>>> ruoshui-ground, job fail alarm feishu send error. Response: {}", result);
            }

        } catch (Exception e) {
            logger.error(">>>>>>>>>>> ruoshui-ground, job fail alarm feishu send exception.", e);
        }
    }

    private static String formatMarkdownContent(String alarmContent, String content) {
        StringBuilder markdown = new StringBuilder();
        
        markdown.append("**告警信息**\n");
        markdown.append("------------------------------\n");
        
        if (alarmContent != null && !alarmContent.isEmpty()) {
            String cleanAlarmContent = alarmContent.replace("<br>", "\n")
                    .replace("<br/>", "\n")
                    .replace("<", "&lt;")
                    .replace(">", "&gt;");
            markdown.append(cleanAlarmContent).append("\n");
        }
        
        markdown.append("------------------------------\n");
        
        if (content != null && !content.isEmpty()) {
            String cleanContent = content.replace("<br>", "\n")
                    .replace("<br/>", "\n")
                    .replace("<", "&lt;")
                    .replace(">", "&gt;")
                    .replaceAll("<[^>]*>", "");
            markdown.append(cleanContent).append("\n");
        }
        
        return markdown.toString();
    }
}