"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.loadConfig = loadConfig;
exports.saveConfig = saveConfig;
exports.parseCLIArgs = parseCLIArgs;
exports.getConfigPathFromCLI = getConfigPathFromCLI;
exports.getMergedConfig = getMergedConfig;
exports.getTempLogsDir = getTempLogsDir;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
/**
 * Load configuration from file or return default
 */
function loadConfig(configPath) {
    const defaultConfigPath = path_1.default.resolve(process.cwd(), 'node.config.json');
    const configFile = configPath || defaultConfigPath;
    let config = {};
    // Try to load from file if it exists
    if (fs_1.default.existsSync(configFile)) {
        try {
            const fileContent = fs_1.default.readFileSync(configFile, 'utf-8');
            config = JSON.parse(fileContent);
        }
        catch (error) {
            console.warn(`Warning: Failed to parse config file ${configFile}:`, error);
        }
    }
    return config;
}
/**
 * Save configuration to file
 */
function saveConfig(config, configPath) {
    const defaultConfigPath = path_1.default.resolve(process.cwd(), 'node.config.json');
    const configFile = configPath || defaultConfigPath;
    try {
        fs_1.default.writeFileSync(configFile, JSON.stringify(config, null, 2), 'utf-8');
    }
    catch (error) {
        console.error(`Failed to save config file ${configFile}:`, error);
    }
}
/**
 * Parse CLI arguments
 */
function parseCLIArgs() {
    const args = process.argv.slice(2);
    const config = {};
    for (let i = 0; i < args.length; i++) {
        const arg = args[i];
        const nextArg = args[i + 1];
        switch (arg) {
            case '--hub-url':
            case '-u':
                if (nextArg) {
                    config.hubUrl = nextArg;
                    i++;
                }
                break;
            case '--access-key':
            case '-a':
                if (nextArg) {
                    config.accessKey = nextArg;
                    i++;
                }
                break;
            case '--token':
            case '-t':
                if (nextArg) {
                    config.token = nextArg;
                    i++;
                }
                break;
            case '--name':
            case '-n':
                if (nextArg) {
                    config.name = nextArg;
                    i++;
                }
                break;
            case '--host':
            case '-h':
                if (nextArg) {
                    config.host = nextArg;
                    i++;
                }
                break;
            case '--os':
                if (nextArg) {
                    config.os = nextArg;
                    i++;
                }
                break;
            case '--tags':
                if (nextArg) {
                    config.tags = nextArg;
                    i++;
                }
                break;
            case '--temp-logs-dir':
                if (nextArg) {
                    config.tempLogsDir = nextArg;
                    i++;
                }
                break;
            case '--config':
            case '-c':
                if (nextArg) {
                    // This will be handled separately
                    i++;
                }
                break;
        }
    }
    return config;
}
/**
 * Get config file path from CLI arguments
 */
function getConfigPathFromCLI() {
    const args = process.argv.slice(2);
    for (let i = 0; i < args.length; i++) {
        if ((args[i] === '--config' || args[i] === '-c') && args[i + 1]) {
            return args[i + 1];
        }
    }
    return undefined;
}
/**
 * Merge config from file, CLI args, and environment variables
 */
function getMergedConfig(configPath) {
    // Config path: explicit arg > CLI (-c) > NODE_CONFIG_PATH env
    const cliConfigPath = getConfigPathFromCLI();
    const envConfigPath = process.env.NODE_CONFIG_PATH;
    let finalConfigPath = configPath || cliConfigPath || envConfigPath;
    // If chosen path does not exist (e.g. wrong path in container), try env path
    if (finalConfigPath &&
        !fs_1.default.existsSync(finalConfigPath) &&
        envConfigPath &&
        envConfigPath !== finalConfigPath &&
        fs_1.default.existsSync(envConfigPath)) {
        finalConfigPath = envConfigPath;
    }
    // Load from file
    const baseConfig = finalConfigPath ? loadConfig(finalConfigPath) : loadConfig();
    // Parse CLI args (excluding config path)
    const cliConfig = parseCLIArgs();
    // Merge: file config < CLI args < environment variables
    const merged = {
        hubUrl: process.env.HUB_URL || cliConfig.hubUrl || baseConfig.hubUrl || '',
        accessKey: process.env.ACCESS_KEY || cliConfig.accessKey || baseConfig.accessKey || '',
        token: process.env.TOKEN || cliConfig.token || baseConfig.token || '',
        name: cliConfig.name || baseConfig.name || '',
        host: cliConfig.host || baseConfig.host || '',
        os: cliConfig.os || baseConfig.os || '',
        tags: cliConfig.tags !== undefined ? cliConfig.tags : (baseConfig.tags ?? null),
        capabilityPortRange: cliConfig.capabilityPortRange || baseConfig.capabilityPortRange,
        chromeDriverPath: cliConfig.chromeDriverPath || baseConfig.chromeDriverPath,
        platform: baseConfig.platform,
        bootedSimulators: baseConfig.bootedSimulators,
        iosDeviceType: baseConfig.iosDeviceType,
        androidDeviceType: baseConfig.androidDeviceType,
        appiumServer: cliConfig.appiumServer || baseConfig.appiumServer,
        tempLogsDir: cliConfig.tempLogsDir || baseConfig.tempLogsDir,
        wdaResignedIpaPath: process.env.WDA_RESIGNED_IPA_PATH || baseConfig.wdaResignedIpaPath,
        androidCleanUpApps: baseConfig.androidCleanUpApps,
        iosCleanUpApps: baseConfig.iosCleanUpApps,
        coordinateLogEnabled: process.env.COORDINATE_LOG_ENABLED === 'true' || baseConfig.coordinateLogEnabled,
        dfStreamerEnabled: baseConfig.dfStreamerEnabled,
        dfStreamer: baseConfig.dfStreamer,
        scrcpy: baseConfig.scrcpy,
        mjpeg: baseConfig.mjpeg,
    };
    return merged;
}
/**
 * Get the temporary logs directory path
 * @param configPath - Optional config path override
 * @returns Absolute path to temp logs directory
 */
function getTempLogsDir(configPath) {
    const config = getMergedConfig(configPath);
    const tempLogsDir = config.tempLogsDir || './tmp';
    // If it's a relative path, resolve it from cwd
    if (!path_1.default.isAbsolute(tempLogsDir)) {
        return path_1.default.resolve(process.cwd(), tempLogsDir);
    }
    return tempLogsDir;
}
//# sourceMappingURL=node.config.js.map