"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getStepConfig = void 0;
const child_process_1 = require("child_process");
const path_1 = __importDefault(require("path"));
const logger_1 = require("./logger");
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 getStepConfig = (file) => {
    const { runner, command, args } = getLanguageBasedRunner(file);
    return new Promise((resolve, reject) => {
        let config = null;
        const child = (0, child_process_1.spawn)(command, [...args, runner, file], {
            stdio: ['inherit', 'inherit', 'inherit', 'ipc'],
        });
        child.on('message', (message) => {
            logger_1.globalLogger.debug('[Config] Read config', { config: message });
            config = message;
            resolve(config);
            child.kill(); // we can kill the child process since we already received the message
        });
        child.on('close', (code) => {
            if (config) {
                return; // Config was already resolved
            }
            else if (code !== 0) {
                reject(`Process exited with code ${code}`);
            }
            else if (!config) {
                reject(`No config found for file ${file}`);
            }
        });
        child.on('error', (error) => {
            if (error.code === 'ENOENT') {
                reject(`Executable ${command} not found`);
            }
            else {
                reject(error);
            }
        });
    });
};
exports.getStepConfig = getStepConfig;
