package com.ruoyi.framework.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

public class JsonToMarkdown {

    /**
     * 将JSON字符串转换为Markdown格式
     */
    public static String convert(String jsonString) {
        try {
            Object json = JSON.parse(jsonString);
            if (json instanceof JSONObject) {
                return processObject((JSONObject) json, 0);
            } else if (json instanceof JSONArray) {
                return processArray((JSONArray) json, 0);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "Invalid JSON format";
    }

    private static String processObject(JSONObject obj, int level) {
        StringBuilder markdown = new StringBuilder();

        // 检查是否适合用表格展示
        boolean useTable = shouldUseTable(obj);

        if (useTable && level == 0) {
            // 根级简单对象使用表格
            markdown.append("| Key | Value |\n");
            markdown.append("| --- | --- |\n");

            for (String key : obj.keySet()) {
                Object value = obj.get(key);
                markdown.append("| ")
                        .append(escapeMarkdown(key))
                        .append(" | ")
                        .append(formatValue(value, level + 1))
                        .append(" |\n");
            }
        } else {
            // 使用列表格式
            for (String key : obj.keySet()) {
                Object value = obj.get(key);
                addIndent(markdown, level);
                markdown.append("- **")
                        .append(escapeMarkdown(key))
                        .append("**: ");

                if (value instanceof JSONObject) {
                    markdown.append("\n").append(processObject((JSONObject) value, level + 1));
                } else if (value instanceof JSONArray) {
                    markdown.append("\n").append(processArray((JSONArray) value, level + 1));
                } else {
                    markdown.append(escapeMarkdown(String.valueOf(value))).append("\n");
                }
            }
        }

        return markdown.toString();
    }

    private static String processArray(JSONArray arr, int level) {
        StringBuilder markdown = new StringBuilder();

        for (int i = 0; i < arr.size(); i++) {
            Object value = arr.get(i);
            addIndent(markdown, level);
            markdown.append("- ");

            if (value instanceof JSONObject) {
                markdown.append("Object:\n").append(processObject((JSONObject) value, level + 1));
            } else if (value instanceof JSONArray) {
                markdown.append("Array:\n").append(processArray((JSONArray) value, level + 1));
            } else {
                markdown.append(escapeMarkdown(String.valueOf(value))).append("\n");
            }
        }

        return markdown.toString();
    }

    private static String formatValue(Object value, int level) {
        if (value instanceof JSONObject) {
            return processObject((JSONObject) value, level);
        } else if (value instanceof JSONArray) {
            return processArray((JSONArray) value, level);
        } else {
            return escapeMarkdown(String.valueOf(value));
        }
    }

    private static boolean shouldUseTable(JSONObject obj) {
        if (obj.isEmpty()) return false;

        for (String key : obj.keySet()) {
            Object value = obj.get(key);
            if (value instanceof JSONObject || value instanceof JSONArray) {
                return false;
            }
        }
        return true;
    }

    private static void addIndent(StringBuilder sb, int level) {
        for (int i = 0; i < level; i++) {
            sb.append("  ");
        }
    }

    private static String escapeMarkdown(String text) {
        if (text == null) return "";

        // 转义Markdown特殊字符
        return text.replace("|", "\\|")
                .replace("*", "\\*")
                .replace("_", "\\_")
                .replace("#", "\\#")
                .replace("`", "\\`");
    }

    // 使用示例
    public static void main(String[] args) {
        String json = "{\"name\":\"John\",\"age\":30,\"hobbies\":[\"reading\",\"swimming\"],\"address\":{\"city\":\"New York\",\"zip\":\"10001\"}}";
        String markdown = convert(json);
        System.out.println(markdown);
    }
}