package com.codechecker.common;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 企微 Markdown 发送（与具体变更类型解耦）。
 */
public class WeComMarkdownSender {
    private static final int MAX_LENGTH = 3800;
    private static final MediaType JSON = MediaType.get("application/json; charset=utf-8");

    private final OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.SECONDS)
            .readTimeout(10, TimeUnit.SECONDS)
            .build();

    public boolean send(String webhookUrl, String content) {
        return postMarkdown(webhookUrl, truncate(content));
    }

    public void logPreview(String title, String content) {
        System.out.println("========== " + title + " ==========");
        System.out.println(content);
        System.out.println("========== 结束 ==========");
    }

    private boolean postMarkdown(String webhookUrl, String content) {
        if (webhookUrl == null || webhookUrl.isBlank() || webhookUrl.contains("YOUR_WECOM")) {
            System.out.println("[警告] 未配置有效的企业微信 Webhook URL");
            System.out.println("--- 通知预览 ---");
            System.out.println(content.length() > 1000 ? content.substring(0, 1000) : content);
            return false;
        }

        String payload = "{\"msgtype\":\"markdown\",\"markdown\":{\"content\":"
                + jsonEscape(content) + "}}";
        Request request = new Request.Builder()
                .url(webhookUrl)
                .post(RequestBody.create(payload, JSON))
                .build();
        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful() && response.body() != null) {
                return response.body().string().contains("\"errcode\":0");
            }
            System.out.println("[错误] 企微返回异常: " + response.code());
            return false;
        } catch (IOException e) {
            System.out.println("[错误] 发送企微消息失败: " + e.getMessage());
            return false;
        }
    }

    private String truncate(String text) {
        if (text.length() <= MAX_LENGTH) {
            return text;
        }
        return text.substring(0, MAX_LENGTH) + "\n\n... 消息过长，已截断";
    }

    private String jsonEscape(String text) {
        String escaped = text
                .replace("\\", "\\\\")
                .replace("\"", "\\\"")
                .replace("\n", "\\n")
                .replace("\r", "");
        return "\"" + escaped + "\"";
    }
}
