"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.debugFailWrapper = debugFailWrapper;
const loggingProvider_1 = require("@mablhq-internal/runtime/providers/logging/loggingProvider");
const chalk = require('chalk');
function debugFailWrapper(func, exitCodeOnError = 1) {
    return async (parsed) => {
        (0, loggingProvider_1.sendLogsToStdErr)();
        let exitCode = 0;
        try {
            await func(parsed);
        }
        catch (error) {
            const err = error instanceof Error ? error : new Error(String(error));
            loggingProvider_1.logger.error(chalk.red.bold(err.message || 'An unexpected error occurred'));
            exitCode = exitCodeOnError;
        }
        await flushStdio();
        const inheritedExitCode = typeof process.exitCode === 'number' ? process.exitCode : 0;
        process.exit(exitCode || inheritedExitCode);
    };
}
async function flushStdio() {
    await flushStream(process.stdout);
    await flushStream(process.stderr);
}
function flushStream(stream) {
    if (stream.destroyed || !stream.writable) {
        return Promise.resolve();
    }
    return new Promise((resolve) => {
        stream.write('', () => resolve());
    });
}
