import { readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { getConfigDir } from "../utils/paths.js";
import { logger } from "../utils/logger.js";
import { DEFAULT_CONFIG, validateConfig } from "./schema.js";
export { DEFAULT_CONFIG, validateConfig } from "./schema.js";
const CONFIG_FILENAME = "config.json";
function getConfigPath() {
    return join(getConfigDir(), CONFIG_FILENAME);
}
/**
 * Deep merge source into target. Only merges plain objects, not arrays.
 * Source values override target values. Undefined source values are skipped.
 */
function deepMerge(target, source) {
    const result = { ...target };
    for (const key of Object.keys(source)) {
        const sourceVal = source[key];
        const targetVal = result[key];
        if (sourceVal === undefined) {
            continue;
        }
        if (sourceVal !== null &&
            typeof sourceVal === "object" &&
            !Array.isArray(sourceVal) &&
            targetVal !== null &&
            typeof targetVal === "object" &&
            !Array.isArray(targetVal)) {
            result[key] = deepMerge(targetVal, sourceVal);
        }
        else {
            result[key] = sourceVal;
        }
    }
    return result;
}
/**
 * Load config from config.json, merging with defaults.
 * Creates default config file if it doesn't exist.
 */
export async function loadConfig() {
    const configPath = getConfigPath();
    try {
        const raw = await readFile(configPath, "utf-8");
        const userConfig = JSON.parse(raw);
        const merged = deepMerge(DEFAULT_CONFIG, userConfig);
        const errors = validateConfig(merged);
        if (errors.length > 0) {
            logger.warn(`Config validation warnings: ${errors.join(", ")}. Using defaults for invalid values.`);
            return DEFAULT_CONFIG;
        }
        return merged;
    }
    catch (err) {
        if (err &&
            typeof err === "object" &&
            "code" in err &&
            err.code === "ENOENT") {
            logger.info("No config.json found, creating default configuration");
            await saveConfig(DEFAULT_CONFIG);
            return DEFAULT_CONFIG;
        }
        if (err instanceof SyntaxError) {
            logger.warn("config.json contains invalid JSON, using defaults");
            return DEFAULT_CONFIG;
        }
        throw err;
    }
}
/**
 * Save config to config.json.
 */
export async function saveConfig(config) {
    const configPath = getConfigPath();
    await writeFile(configPath, JSON.stringify(config, null, 2) + "\n", "utf-8");
}
//# sourceMappingURL=index.js.map