"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const path_1 = __importDefault(require("path"));
const logger_1 = require("./logger");
const rpc_state_manager_1 = require("./rpc-state-manager");
const rpc_1 = require("./rpc");
const middleware_compose_1 = require("./middleware-compose");
// eslint-disable-next-line @typescript-eslint/no-require-imports
require('dotenv').config();
// Add ts-node registration before dynamic imports
// eslint-disable-next-line @typescript-eslint/no-require-imports
require('ts-node').register({
    transpileOnly: true,
    compilerOptions: { module: 'commonjs' },
});
function parseArgs(arg) {
    try {
        return JSON.parse(arg);
    }
    catch {
        return arg;
    }
}
async function runTypescriptModule(filePath, event) {
    try {
        // eslint-disable-next-line @typescript-eslint/no-require-imports
        const module = require(path_1.default.resolve(filePath));
        // Check if the specified function exists in the module
        if (typeof module.handler !== 'function') {
            throw new Error(`Function handler not found in module ${filePath}`);
        }
        const { traceId, flows, contextInFirstArg } = event;
        const sender = new rpc_1.RpcSender(process);
        const logger = new logger_1.Logger(traceId, flows, sender);
        const state = new rpc_state_manager_1.RpcStateManager(sender);
        const emit = async (data) => sender.send('emit', data);
        const context = { traceId, flows, logger, state, emit };
        sender.init();
        const middlewares = Array.isArray(module.config.middleware) ? module.config.middleware : [];
        const composedMiddleware = (0, middleware_compose_1.composeMiddleware)(...middlewares);
        const handlerFn = () => {
            return contextInFirstArg ? module.handler(context) : module.handler(event.data, context);
        };
        const result = await composedMiddleware(event.data, context, handlerFn);
        await sender.send('result', result);
        await sender.close();
        process.exit(0);
    }
    catch (error) {
        console.error('Error running TypeScript module:', error);
        process.exit(1);
    }
}
const [, , filePath, arg] = process.argv;
if (!filePath) {
    console.error('Usage: node nodeRunner.js <file-path> <arg>');
    process.exit(1);
}
runTypescriptModule(filePath, parseArgs(arg)).catch((err) => {
    console.error('Error:', err);
    process.exit(1);
});
