package com.smqjh.agent.mcp;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.node.ObjectNode;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

final class Jsons {
    static final ObjectMapper MAPPER = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);

    private Jsons() {
    }

    static JsonNode read(Path path) throws IOException {
        String content = Files.readString(path);
        if (!content.isEmpty() && content.charAt(0) == '\uFEFF') {
            content = content.substring(1);
        }
        return MAPPER.readTree(content);
    }

    static ObjectNode object() {
        return MAPPER.createObjectNode();
    }

    static ObjectNode toObject(Object value) {
        return MAPPER.valueToTree(value);
    }

    static String stringify(Object value) {
        try {
            return MAPPER.writeValueAsString(value);
        } catch (JsonProcessingException error) {
            throw new IllegalStateException(error);
        }
    }

    static void deepMerge(ObjectNode target, JsonNode patch) {
        if (patch == null || !patch.isObject()) {
            return;
        }
        patch.fields().forEachRemaining(entry -> {
            JsonNode existing = target.get(entry.getKey());
            JsonNode value = entry.getValue();
            if (existing != null && existing.isObject() && value.isObject()) {
                deepMerge((ObjectNode) existing, value);
            } else {
                target.set(entry.getKey(), value);
            }
        });
    }
}
