package com.smqjh.agent.mcp;

import com.fasterxml.jackson.databind.node.ObjectNode;

import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;

final class ConfigLoader {
    private ConfigLoader() {
    }

    static AppConfig load(Path baseDir) throws Exception {
        ObjectNode root = Jsons.toObject(new AppConfig());

        Path desktopConfig = desktopConfigPath();
        if (Files.exists(desktopConfig)) {
            Jsons.deepMerge(root, Jsons.read(desktopConfig));
            root.put("desktopConfigPath", desktopConfig.toString());
        }

        Path localConfig = baseDir.resolve("config").resolve("local.json");
        if (Files.exists(localConfig)) {
            Jsons.deepMerge(root, Jsons.read(localConfig));
        }

        AppConfig config = Jsons.MAPPER.treeToValue(root, AppConfig.class);
        applyEnv(config, System.getenv());
        return config;
    }

    private static Path desktopConfigPath() {
        String explicit = System.getenv("SMQJH_DESKTOP_CONFIG");
        if (hasText(explicit)) {
            return Path.of(explicit);
        }
        String appData = System.getenv("APPDATA");
        if (!hasText(appData)) {
            return Path.of("config", "missing-desktop-config.json");
        }
        return Path.of(appData, "smqjh-admin-agent", "config.json");
    }

    private static void applyEnv(AppConfig config, Map<String, String> env) {
        config.baseUrl = envOr(config.baseUrl, env.get("SMQJH_BASE_URL"));
        config.tenantCode = envOr(config.tenantCode, env.get("SMQJH_TENANT_CODE"));
        config.tenantDomain = envOr(config.tenantDomain, env.get("SMQJH_TENANT_DOMAIN"));
        config.mcp.host = envOr(config.mcp.host, env.get("SMQJH_MCP_HOST"));
        config.mcp.path = envOr(config.mcp.path, env.get("SMQJH_MCP_PATH"));
        config.mcp.authToken = envOr(config.mcp.authToken, env.get("SMQJH_MCP_TOKEN"));
        config.mcp.port = intOr(config.mcp.port, env.get("SMQJH_MCP_PORT"));
        config.mcp.allowExternal = boolOr(config.mcp.allowExternal, env.get("SMQJH_MCP_ALLOW_EXTERNAL"));
        config.database.host = envOr(config.database.host, env.get("SMQJH_DB_HOST"));
        config.database.database = envOr(config.database.database, env.get("SMQJH_DB_NAME"));
        config.database.username = envOr(config.database.username, env.get("SMQJH_DB_USER"));
        config.database.password = envOr(config.database.password, env.get("SMQJH_DB_PASSWORD"));
        config.database.port = intOr(config.database.port, env.get("SMQJH_DB_PORT"));
        config.deepSeek.apiKey = envOr(config.deepSeek.apiKey, env.get("DEEPSEEK_API_KEY"));
    }

    private static String envOr(String current, String value) {
        return hasText(value) ? value.trim() : current;
    }

    private static int intOr(int current, String value) {
        if (!hasText(value)) {
            return current;
        }
        try {
            return Integer.parseInt(value.trim());
        } catch (NumberFormatException ignored) {
            return current;
        }
    }

    private static boolean boolOr(boolean current, String value) {
        if (!hasText(value)) {
            return current;
        }
        return "true".equalsIgnoreCase(value.trim()) || "1".equals(value.trim());
    }

    private static boolean hasText(String value) {
        return value != null && !value.trim().isEmpty();
    }
}
