"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConfigLoader = void 0;
const fs = __importStar(require("fs-extra"));
const path = __importStar(require("path"));
const yaml = __importStar(require("yaml"));
class ConfigLoader {
    static async load(configPath) {
        if (!await fs.pathExists(configPath)) {
            throw new Error(`Configuration file not found: ${configPath}`);
        }
        const content = await fs.readFile(configPath, 'utf-8');
        const ext = path.extname(configPath).toLowerCase();
        let config;
        switch (ext) {
            case '.json':
                config = JSON.parse(content);
                break;
            case '.yaml':
            case '.yml':
                config = yaml.parse(content);
                break;
            default:
                // Try to detect format
                try {
                    config = JSON.parse(content);
                }
                catch {
                    try {
                        config = yaml.parse(content);
                    }
                    catch {
                        throw new Error(`Unable to parse configuration file: ${configPath}`);
                    }
                }
        }
        // Expand environment variables
        config = this.expandEnvironmentVariables(config);
        return config;
    }
    static expandEnvironmentVariables(obj) {
        if (typeof obj === 'string') {
            // Replace ${VAR} with environment variable value
            return obj.replace(/\$\{([^}]+)\}/g, (match, varName) => {
                return process.env[varName] || match;
            });
        }
        if (Array.isArray(obj)) {
            return obj.map(item => this.expandEnvironmentVariables(item));
        }
        if (obj && typeof obj === 'object') {
            const result = {};
            for (const [key, value] of Object.entries(obj)) {
                result[key] = this.expandEnvironmentVariables(value);
            }
            return result;
        }
        return obj;
    }
    static async save(configPath, config) {
        await fs.ensureDir(path.dirname(configPath));
        const ext = path.extname(configPath).toLowerCase();
        let content;
        switch (ext) {
            case '.json':
                content = JSON.stringify(config, null, 2);
                break;
            case '.yaml':
            case '.yml':
                content = yaml.stringify(config);
                break;
            default:
                // Default to YAML
                content = yaml.stringify(config);
        }
        await fs.writeFile(configPath, content, 'utf-8');
    }
    static async merge(base, override) {
        return this.deepMerge(base, override);
    }
    static deepMerge(target, source) {
        if (!source)
            return target;
        if (!target)
            return source;
        if (Array.isArray(source)) {
            return source;
        }
        if (typeof source !== 'object' || source === null) {
            return source;
        }
        const result = { ...target };
        for (const key in source) {
            if (source.hasOwnProperty(key)) {
                if (typeof source[key] === 'object' && source[key] !== null && !Array.isArray(source[key])) {
                    result[key] = this.deepMerge(target[key], source[key]);
                }
                else {
                    result[key] = source[key];
                }
            }
        }
        return result;
    }
}
exports.ConfigLoader = ConfigLoader;
//# sourceMappingURL=config.js.map