"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.startExecutor = startExecutor;
exports.getExecutor = getExecutor;
const executor_service_1 = require("./executor/executor.service");
const logger_1 = require("./utils/logger");
require("./sentry");
const prometheus_1 = require("./prometheus");
// This file is dedicated for executor library
// and is not used in the main process.
// It is used by the consumers of the library.
let executor;
async function shutdownHandler(executor) {
    if (executor.isShutdownInProgress()) {
        logger_1.logger.info('🚫 Shutdown is already in progress...');
        return;
    }
    await executor.triggerShutdown();
    logger_1.logger.info('Shut-down sequence complete. Bye bye 👋');
    process.exit(0);
}
/**
 * Creates and initializes the executor instance without starting it.
 */
async function createExecutorInstance() {
    if (executor)
        return executor;
    const config = (await Promise.resolve().then(() => __importStar(require(`./config/config`)))).default;
    const prometheus = new prometheus_1.Prometheus(config, config.prometheus.port);
    logger_1.logger.info('🚀 Creating Executor');
    logger_1.logger.info(`💿 Version: ${config.version}`);
    executor = new executor_service_1.Executor(config, prometheus);
    await executor.init();
    return executor;
}
/**
 * Starts the executor instance.
 */
async function startExecutor() {
    if (!executor) {
        await createExecutorInstance();
    }
    executor.start();
}
/**
 * Gets the executor instance.
 * Initializes the instance if it does not exist.
 */
async function getExecutor() {
    if (!executor) {
        return await createExecutorInstance();
    }
    const pricerApi = executor.getPricerApi();
    const id = executor.getMyAddress();
    try {
        await pricerApi.insertAIxecutor(id);
    }
    catch (error) {
        logger_1.logger.warn({ id, error: error.message }, 'Could not insert AIxecutor, will retry later.');
    }
    return executor;
}
process.on('SIGINT', async () => {
    logger_1.logger.warn('Received SIGINT signal. Shutting down...');
    await shutdownHandler(executor);
});
process.on('SIGTERM', async () => {
    logger_1.logger.warn('Received SIGTERM signal. Shutting down...');
    await shutdownHandler(executor);
});
//# sourceMappingURL=aixecutor.js.map