import { readFileSync, existsSync } from "node:fs";
import { resolve, dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { homedir } from "node:os";
import { logger } from "./utils/logger.js";
const DEFAULT_WORKBENCH_PATH = "C:\\Program Files (x86)\\Steam\\steamapps\\common\\Arma Reforger Tools";
const DEFAULTS = {
    workbenchPath: DEFAULT_WORKBENCH_PATH,
    projectPath: join(homedir(), "Documents", "My Games", "ArmaReforgerWorkbench", "addons"),
    gamePath: resolve(DEFAULT_WORKBENCH_PATH, "..", "Arma Reforger"),
    dataDir: resolve(dirname(fileURLToPath(import.meta.url)), "..", "data"),
    patternsDir: resolve(dirname(fileURLToPath(import.meta.url)), "..", "data", "patterns"),
    workbenchHost: "127.0.0.1",
    workbenchPort: 5775,
};
function loadJsonFile(path) {
    try {
        if (existsSync(path)) {
            const raw = readFileSync(path, "utf-8");
            return JSON.parse(raw);
        }
    }
    catch (e) {
        logger.warn(`Failed to load config from ${path}: ${e}`);
    }
    return {};
}
export function loadConfig() {
    // 1. Start with defaults
    const config = { ...DEFAULTS };
    // 2. Package-local config file
    const localConfigPath = resolve(dirname(fileURLToPath(import.meta.url)), "..", "enfusion-mcp.config.json");
    Object.assign(config, loadJsonFile(localConfigPath));
    // 3. User home config
    const homeConfigPath = resolve(homedir(), ".enfusion-mcp", "config.json");
    Object.assign(config, loadJsonFile(homeConfigPath));
    // 4. Environment variables override everything
    if (process.env.ENFUSION_WORKBENCH_PATH) {
        config.workbenchPath = process.env.ENFUSION_WORKBENCH_PATH;
    }
    if (process.env.ENFUSION_PROJECT_PATH) {
        config.projectPath = process.env.ENFUSION_PROJECT_PATH;
    }
    if (process.env.ENFUSION_GAME_PATH) {
        config.gamePath = process.env.ENFUSION_GAME_PATH;
    }
    if (process.env.ENFUSION_MCP_DATA_DIR) {
        config.dataDir = process.env.ENFUSION_MCP_DATA_DIR;
    }
    if (process.env.ENFUSION_WORKBENCH_HOST) {
        config.workbenchHost = process.env.ENFUSION_WORKBENCH_HOST;
    }
    if (process.env.ENFUSION_WORKBENCH_PORT) {
        const port = parseInt(process.env.ENFUSION_WORKBENCH_PORT, 10);
        if (!isNaN(port) && port > 0 && port < 65536) {
            config.workbenchPort = port;
        }
    }
    // Auto-derive gamePath from workbenchPath if not explicitly set
    if (!process.env.ENFUSION_GAME_PATH && config.workbenchPath !== DEFAULT_WORKBENCH_PATH) {
        config.gamePath = resolve(config.workbenchPath, "..", "Arma Reforger");
    }
    logger.debug("Config loaded", config);
    return config;
}
//# sourceMappingURL=config.js.map