package com.common.util;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.JsonNodeType;
import com.common.entity.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.*;
import java.util.Map.Entry;
import org.json.JSONObject;
import org.json.JSONArray;
import com.fasterxml.jackson.core.type.TypeReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class JsonParser  {

    private static final ObjectMapper objectMapper = new ObjectMapper();
    private static final Logger logger = LoggerFactory.getLogger(JsonParser.class);

    public static void main(String[] args) {
        String logMessage = "<15>Sep 24 12:06:59 LAPTOP-ARDUR3N0 <15>2025-09-24T11:52:26Z 5f46d3be75e1 supermario 128 honeypot_event - ﻿{\"source\":\"honeypot\",\"id\":\"f6a13c35-bf9d-4da6-a181-50ce23e7ef6a\",\"start_time\":\"2023-09-03T11:07:02.50167643Z\",\"time\":\"2023-09-03T11:16:18.883885281Z\",\"risk_level\":4,\"connection\":\"b18f3fbe-3fbf-4495-815f-ff26f6fb0bdf\",\"file_info\":null,\"extra\":{\"payload\":{\"format\":\"line\",\"name\":{\"cn\":\"攻击载荷\",\"en\":\"payload\"},\"value\":\"\"},\"uid\":{\"format\":\"line\",\"name\":{\"cn\":\"\",\"en\":\"\"},\"uid\":\"b4cbc73c-25d0-4429-ae1b-a856cdf1a651\",\"value\":\"\"}},\"type\":\"WEB_ATTACK_SCANNER\",\"agent_sn\":\"caa7da42-0cca-4cb1-b501-1f1eb2b588d5\",\"agent_name\":\" 教育局蜜罐探针\",\"honeypot_id\":\"11a9ac6bdf38ae2aaa49ec4f1b4a921bff71952cb9f175bdd8ee1f0497057bc6\",\"honeypot_name\":\"茂名市中小学管理平台管理后台\",\"src_ip\":\"117.50.189.7\",\"src_port\":58512,\"src_mac\":\"\",\"dest_ip\":\"192.168.222.2\",\"dest_port\":9200,\"proxy_ip\":null,\"node\":\"WRx3\"}";
        System.out.println(logMessage);
        try {
            XdrHoneypot xdrHoneypot = parseLogMessageToXdrHoneypot(logMessage);
            System.out.println("解析成功！");
            System.out.println(xdrHoneypot);
        } catch (Exception e) {
            System.err.println("解析失败: " + e.getMessage());
            e.printStackTrace();
        }

        // 多层嵌套 JSON
        String complexJson = "{\"source\":\"honeypot1\",\"id\":\"f6a13c35-bf9d-4da6-a181-50ce23e7ef6a\",\"start_time\":\"2023-09-03T11:07:02.50167643Z\",\"time\":\"2023-09-03T11:16:18.883885281Z\",\"risk_level\":4,\"connection\":\"b18f3fbe-3fbf-4495-815f-ff26f6fb0bdf\",\"file_info\":null,\"extra\":{\"payload\":{\"format\":\"line\",\"name\":{\"cn\":\"攻击载荷\",\"en\":\"payload\"},\"value\":\"\"},\"uid\":{\"format\":\"line\",\"name\":{\"cn\":\"\",\"en\":\"\"},\"uid\":\"b4cbc73c-25d0-4429-ae1b-a856cdf1a651\",\"value\":\"\"}},\"type\":\"WEB_ATTACK_SCANNER\",\"agent_sn\":\"caa7da42-0cca-4cb1-b501-1f1eb2b588d5\",\"agent_name\":\" 教育局蜜罐探针\",\"honeypot_id\":\"11a9ac6bdf38ae2aaa49ec4f1b4a921bff71952cb9f175bdd8ee1f0497057bc6\",\"honeypot_name\":\"茂名市中小学管理平台管理后台\",\"src_ip\":\"117.50.189.7\",\"src_port\":58512,\"src_mac\":\"\",\"dest_ip\":\"192.168.222.2\",\"dest_port\":9200,\"proxy_ip\":null,\"node\":\"WRx3\"}";

        System.out.println("=== 扁平化 Map 解析结果 ===");
        Map<String, Object> flatMap = parseJsonToFlatMap(complexJson);
        flatMap.forEach((key, value) -> System.out.println(key + " = " + value));

        System.out.println("\n=== 嵌套结构 Map 解析结果 ===");
        Map<String, Object> nestedMap = parseJsonToNestedMap(complexJson);
        printMap(nestedMap);

        System.out.println("\n=== 特定值访问示例 ===");
        // 访问特定值
        System.out.println("extra.payload.format: " + flatMap.get("extra.payload.format"));
        System.out.println("extra.payload.format: " + flatMap.get("extra.payload.name.cn"));
    }

    /**
     * 从日志消息中解析 JSON 并转换为 XdrHoneypot 对象
     */
    public static XdrHoneypot parseLogMessageToXdrHoneypot(String logMessage) throws Exception {
        // 1. 提取 JSON 部分
        String jsonString = extractJsonFromLogMessage(logMessage);

        // 2. 解析 JSON
        JsonNode jsonNode = objectMapper.readTree(jsonString);

        // 3. 创建并填充 XdrHoneypot 对象
        XdrHoneypot xdrHoneypot = new XdrHoneypot();

        // 设置字段值
        xdrHoneypot.setVcsource(getStringValue(jsonNode, "source"));
        xdrHoneypot.setDstartTime(getStringValue(jsonNode, "start_time"));
        xdrHoneypot.setDtime(getStringValue(jsonNode, "time"));
        xdrHoneypot.setRiskLevel(getStringValue(jsonNode, "risk_level"));
        xdrHoneypot.setVcconnection(getStringValue(jsonNode, "connection"));
        xdrHoneypot.setFileInfo(getStringValue(jsonNode, "file_info"));
        xdrHoneypot.setExtra(getExtraAsString(jsonNode.get("extra")));
        xdrHoneypot.setVctype(getStringValue(jsonNode, "type"));
        xdrHoneypot.setAgentSn(getStringValue(jsonNode, "agent_sn"));
        xdrHoneypot.setAgentName(getStringValue(jsonNode, "agent_name"));
        xdrHoneypot.setHoneypotId(getStringValue(jsonNode, "honeypot_id"));
        xdrHoneypot.setHoneypotName(getStringValue(jsonNode, "honeypot_name"));
        xdrHoneypot.setSrcIp(getStringValue(jsonNode, "src_ip"));
        xdrHoneypot.setSrcPort(getStringValue(jsonNode, "src_port"));
        xdrHoneypot.setSrcMac(getStringValue(jsonNode, "src_mac"));
        xdrHoneypot.setDestIp(getStringValue(jsonNode, "dest_ip"));
        xdrHoneypot.setDestPort(getStringValue(jsonNode, "dest_port"));
        xdrHoneypot.setProxyIp(getStringValue(jsonNode, "proxy_ip"));
        xdrHoneypot.setNode(getStringValue(jsonNode, "node"));
        xdrHoneypot.setCreateTime(LocalDateTime.now());

        return xdrHoneypot;
    }

    /**
     * 从日志消息中提取 JSON 部分
     */
    public  static String extractJsonFromLogMessage(String logMessage) {
        // 查找第一个 { 和最后一个 } 的位置
        int startIndex = logMessage.indexOf('{');
        int endIndex = logMessage.lastIndexOf('}');

        if (startIndex == -1 || endIndex == -1 || endIndex <= startIndex) {
            throw new IllegalArgumentException("日志消息中未找到有效的 JSON 内容");
        }
        return logMessage.substring(startIndex, endIndex + 1);

    }

    /**
     * 安全地获取字符串值
     */
    private static String getStringValue(JsonNode jsonNode, String fieldName) {
        JsonNode fieldNode = jsonNode.get(fieldName);
        if (fieldNode == null || fieldNode.isNull()) {
            return null;
        }

        if (fieldNode.isTextual()) {
            return fieldNode.asText();
        } else {
            // 对于非文本类型（如数字），转换为字符串
            return fieldNode.toString();
        }
    }

    /**
     * 将 extra 字段转换为 JSON 字符串
     */
    private static String getExtraAsString(JsonNode extraNode) {
        if (extraNode == null || extraNode.isNull()) {
            return null;
        }
        try {
            return objectMapper.writeValueAsString(extraNode);
        } catch (Exception e) {
            // 如果序列化失败，返回原始字符串
            return extraNode.toString();
        }
    }


    /**
     * 解析 JSON 字符串为扁平化的 Map
     * @param jsonStr JSON 字符串
     * @return 扁平化的 Map，key 使用点号表示嵌套路径
     */
    public static LinkedHashMap<String, Object> parseJsonToFlatMap(String jsonStr) {
        try {
            LinkedHashMap<String, Object> resultMap = new LinkedHashMap<>();
            if(!isValidJson(jsonStr))
            {
                System.out.println("parseJsonToFlatMap() json str:"+jsonStr);
                System.out.println("isValidJson(string) is false");
                return null;
            }

            TypeReference<Map<String, Object>> typeRef = new TypeReference<Map<String, Object>>() {};
            Object jsonObject =  objectMapper.readValue(jsonStr, typeRef);
            //Object jsonObject = objectMapper.readValue(jsonStr.trim(), Object.class);
            flattenJson("", jsonObject, resultMap);
            return resultMap;
        } catch (Exception e) {
            //System.out.println("Exception ex.message:"+ e.getMessage());
            logger.error("parseJsonToFlatMap  ex.message:{}", e.getMessage());
            throw new RuntimeException("parseJsonToFlatMap JSON 解析失败", e);
        }
    }

    /**
     * 递归扁平化 JSON 对象
     */
    private static void flattenJson(String currentPath, Object jsonObject, Map<String, Object> resultMap) {

        try {
            if (jsonObject instanceof Map) {
                // 处理 JSON 对象
                Map<?, ?> map = (Map<?, ?>) jsonObject;
                for (Entry<?, ?> entry : map.entrySet()) {
                    String key = entry.getKey().toString();
                    String newPath = currentPath.isEmpty() ? key : currentPath + "." + key;
                    flattenJson(newPath, entry.getValue(), resultMap);
                }
            } else if (jsonObject instanceof List) {
                // 处理 JSON 数组
                List<?> list = (List<?>) jsonObject;
                for (int i = 0; i < list.size(); i++) {
                    String newPath = currentPath + "[" + i + "]";
                    flattenJson(newPath, list.get(i), resultMap);
                }
            } else {
                // 基本类型值
                resultMap.put(currentPath, jsonObject);
            }

        } catch (Exception e) {
            System.out.println("Exception ex.message:"+ e.getMessage());

            throw new RuntimeException("flattenJson 处理异常", e);
        }
    }

    /**
     * 保持嵌套结构的 JSON 解析
     */
    public static Map<String, Object> parseJsonToNestedMap(String jsonStr) {
        try {
            return objectMapper.readValue(jsonStr, Map.class);
        } catch (Exception e) {
            throw new RuntimeException("parseJsonToNestedMap() JSON 解析失败", e);
        }
    }
    /**
     * 打印 Map 内容
     */
    public static void printMap(Map<String, Object> map) {
        printMap("", map, 0);
}

    private static void printMap(String prefix, Map<String, Object> map, int indent) {
       // String indentStr = "  ".repeat(indent);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < indent; i++) {
            sb.append(" ");
        }
        String indentStr = sb.toString();

        for (Entry<String, Object> entry : map.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            String fullKey = prefix.isEmpty() ? key : prefix + "." + key;

            if (value instanceof Map) {
                System.out.println(indentStr + key + ":");
                printMap(fullKey, (Map<String, Object>) value, indent + 1);
            } else if (value instanceof List) {
                System.out.println(indentStr + key + ":");
                printList(fullKey, (List<Object>) value, indent + 1);
            } else {
                System.out.println(indentStr + key + " = " + value);
            }
        }
    }

    private static void printList(String prefix, List<Object> list, int indent) {
        //String indentStr = "  ".repeat(indent);

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < indent; i++) {
            sb.append(" ");
        }
        String indentStr = sb.toString();
        for (int i = 0; i < list.size(); i++) {
            Object value = list.get(i);
            String itemKey = prefix + "[" + i + "]";

            if (value instanceof Map) {
                System.out.println(indentStr + "[" + i + "]:");
                printMap(itemKey, (Map<String, Object>) value, indent + 1);
            } else if (value instanceof List) {
                System.out.println(indentStr + "[" + i + "]:");
                printList(itemKey, (List<Object>) value, indent + 1);
            } else {
                System.out.println(indentStr + "[" + i + "] = " + value);
            }
        }
    }




    /**
     * 将 JSONObject 转换为 Map
     */
    public static LinkedHashMap<String, Object> jsonToMap(String jsonString) {
        try {
            JSONObject jsonObject = new JSONObject(jsonString.trim());
            return toMap(jsonObject);
        } catch (Exception e) {
            throw new RuntimeException("jsonToMap 转换失败: " + e.getMessage(), e);
        }
    }

    /**
     * 递归转换 JSONObject 到 Map
     */
    private static LinkedHashMap<String, Object> toMap(JSONObject jsonObject) {
        LinkedHashMap<String, Object> map = new LinkedHashMap<>();
        Iterator<String> keys = jsonObject.keys();

        while (keys.hasNext()) {
            String key = keys.next();
            Object value = jsonObject.get(key);

            if (value instanceof JSONObject) {
                // 嵌套对象
                value = toMap((JSONObject) value);
            } else if (value instanceof JSONArray) {
                // 数组
                value = toList((JSONArray) value);
            }

            map.put(key, value);
        }
        return map;
    }

    /**
     * 递归转换 JSONArray 到 List
     */
    private static List<Object> toList(JSONArray array) {
        List<Object> list = new ArrayList<>();
        for (int i = 0; i < array.length(); i++) {
            Object value = array.get(i);
            if (value instanceof JSONObject) {
                value = toMap((JSONObject) value);
            } else if (value instanceof JSONArray) {
                value = toList((JSONArray) value);
            }
            list.add(value);
        }
        return list;
    }



    /**
     * 预处理 JSON 字符串
     */
    public static Optional<String> preprocessJson(String jsonString) {
        if (jsonString == null) {
            return Optional.empty();
        }
        String trimmed = jsonString.trim();
        // 处理空字符串
        if (trimmed.isEmpty()) {
            return Optional.empty();
        }
        // 处理 BOM
        if (trimmed.startsWith("\uFEFF")) {
            trimmed = trimmed.substring(1).trim();
            if (trimmed.isEmpty()) {
                return Optional.empty();
            }
        }

        return Optional.of(trimmed);
    }

    /**
     * 检查 JSON 字符串是否有效
     */
    public static boolean isValidJson(String jsonString) {
        return preprocessJson(jsonString).isPresent();
    }

}
