package com.kingdee.eas.custom.integration.weaver.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.Map;

/**
 * 读取与 base 相同的 INTEGRATION_CONFIG_PATH / classpath integration-config.json 中的 weaver 节点。
 * 不改 IntegrationConfigService，避免动 base。
 */
@Service
public class WeaverConfigService implements InitializingBean {

    private static final Logger log = LoggerFactory.getLogger(WeaverConfigService.class);
    private static final String CLASSPATH_CONFIG = "integration-config.json";

    private final ObjectMapper objectMapper = new ObjectMapper();
    private final String externalConfigPath = System.getenv("INTEGRATION_CONFIG_PATH");

    private volatile WeaverConfig weaverConfig = new WeaverConfig();
    private volatile long lastModified = -1L;

    @Override
    public void afterPropertiesSet() {
        reloadQuietly();
    }

    public WeaverConfig getWeaverConfig() {
        refreshIfNeeded();
        return weaverConfig;
    }

    private void refreshIfNeeded() {
        if (externalConfigPath == null || externalConfigPath.trim().isEmpty()) {
            return;
        }
        try {
            Path path = Paths.get(externalConfigPath);
            if (!Files.exists(path)) {
                return;
            }
            long mtime = Files.getLastModifiedTime(path).toMillis();
            if (mtime != lastModified) {
                reloadQuietly();
            }
        } catch (Exception e) {
            log.warn("检查 weaver 配置变更失败: {}", e.getMessage());
        }
    }

    @SuppressWarnings("unchecked")
    private void reloadQuietly() {
        try {
            Map<String, Object> root = loadRoot();
            Object weaverNode = root.get("weaver");
            if (weaverNode instanceof Map) {
                this.weaverConfig = new WeaverConfig((Map<String, String>) weaverNode);
                log.info("WeaverConfig 加载完成: {}", this.weaverConfig);
            } else {
                log.warn("integration-config 缺少 weaver 节点");
                this.weaverConfig = new WeaverConfig();
            }
            if (externalConfigPath != null && !externalConfigPath.trim().isEmpty()) {
                Path path = Paths.get(externalConfigPath);
                if (Files.exists(path)) {
                    lastModified = Files.getLastModifiedTime(path).toMillis();
                }
            }
        } catch (Exception e) {
            log.error("WeaverConfig 加载失败，保留旧值: {}", e.getMessage(), e);
        }
    }

    @SuppressWarnings("unchecked")
    private Map<String, Object> loadRoot() throws IOException {
        if (externalConfigPath != null && !externalConfigPath.trim().isEmpty()) {
            Path path = Paths.get(externalConfigPath);
            if (!Files.exists(path)) {
                throw new IOException("外部配置不存在: " + externalConfigPath);
            }
            try (InputStream is = Files.newInputStream(path)) {
                return objectMapper.readValue(is, Map.class);
            }
        }
        try (InputStream is = Thread.currentThread().getContextClassLoader()
                .getResourceAsStream(CLASSPATH_CONFIG)) {
            if (is == null) {
                return Collections.emptyMap();
            }
            return objectMapper.readValue(is, Map.class);
        }
    }
}
