"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getStreamConfig = exports.getStepConfig = void 0;
const path_1 = __importDefault(require("path"));
const logger_1 = require("./logger");
const process_manager_1 = require("./process-communication/process-manager");
const getLanguageBasedRunner = (stepFilePath = '') => {
    const isPython = stepFilePath.endsWith('.py');
    const isRuby = stepFilePath.endsWith('.rb');
    const isNode = stepFilePath.endsWith('.js') || stepFilePath.endsWith('.ts');
    if (isPython) {
        const pythonRunner = path_1.default.join(__dirname, 'python', 'get-config.py');
        return { runner: pythonRunner, command: 'python', args: [] };
    }
    else if (isRuby) {
        const rubyRunner = path_1.default.join(__dirname, 'ruby', 'get-config.rb');
        return { runner: rubyRunner, command: 'ruby', args: [] };
    }
    else if (isNode) {
        if (process.env._MOTIA_TEST_MODE === 'true') {
            const nodeRunner = path_1.default.join(__dirname, 'node', 'get-config.ts');
            return { runner: nodeRunner, command: 'node', args: ['-r', 'ts-node/register'] };
        }
        const nodeRunner = path_1.default.join(__dirname, 'node', 'get-config.js');
        return { runner: nodeRunner, command: 'node', args: [] };
    }
    throw Error(`Unsupported file extension ${stepFilePath}`);
};
const getConfig = (file) => {
    const { runner, command, args } = getLanguageBasedRunner(file);
    return new Promise((resolve, reject) => {
        let config = null;
        const processManager = new process_manager_1.ProcessManager({
            command,
            args: [...args, runner, file],
            logger: logger_1.globalLogger,
            context: 'Config'
        });
        processManager.spawn().then(() => {
            processManager.onMessage((message) => {
                config = message;
                logger_1.globalLogger.debug(`[Config] Read config via ${processManager.commType?.toUpperCase()}`, {
                    config,
                    communicationType: processManager.commType
                });
                resolve(config);
                processManager.kill();
            });
            processManager.onProcessClose((code) => {
                processManager.close();
                if (config) {
                    return;
                }
                else if (code !== 0) {
                    reject(`Process exited with code ${code}`);
                }
                else if (!config) {
                    reject(`No config found for file ${file}`);
                }
            });
            processManager.onProcessError((error) => {
                processManager.close();
                if (error.code === 'ENOENT') {
                    reject(`Executable ${command} not found`);
                }
                else {
                    reject(error);
                }
            });
        }).catch((error) => {
            reject(`Failed to spawn process: ${error}`);
        });
    });
};
const getStepConfig = (file) => {
    return getConfig(file);
};
exports.getStepConfig = getStepConfig;
const getStreamConfig = (file) => {
    return getConfig(file);
};
exports.getStreamConfig = getStreamConfig;
