import { logger } from './logger.js';
let screen = null;
let restoreHandlersAttached = false;
/**
 * Register screen for terminal restore
 */
export function registerScreen(s) {
    screen = s;
    if (!restoreHandlersAttached) {
        attachRestoreHandlers();
    }
}
/**
 * Restore terminal to safe state
 */
export function restoreTerminal() {
    try {
        // Destroy screen if it exists
        if (screen) {
            try {
                screen.destroy();
            }
            catch (error) {
                // Ignore destroy errors
            }
            screen = null;
        }
        // Reset terminal state
        // \x1b[0m = reset colors
        // \x1b[?25h = show cursor
        // \x1b[?1000l = disable mouse
        process.stdout.write('\x1b[0m\x1b[?25h\x1b[?1000l');
        process.stderr.write('\x1b[0m\x1b[?25h\x1b[?1000l');
        logger.debug('Terminal restored');
    }
    catch (error) {
        // Ignore restore errors - we're exiting anyway
    }
}
/**
 * Attach exit handlers
 */
function attachRestoreHandlers() {
    if (restoreHandlersAttached) {
        return;
    }
    restoreHandlersAttached = true;
    // SIGINT (Ctrl+C)
    process.on('SIGINT', () => {
        logger.warn('SIGINT received - exiting');
        restoreTerminal();
        process.exit(0);
    });
    // SIGTERM
    process.on('SIGTERM', () => {
        logger.warn('SIGTERM received - exiting');
        restoreTerminal();
        process.exit(0);
    });
    // Uncaught exception
    process.on('uncaughtException', (error) => {
        logger.error(`Uncaught exception: ${error.message}`);
        if (error.stack) {
            logger.error(`Stack: ${error.stack}`);
        }
        restoreTerminal();
        process.exit(1);
    });
    // Unhandled rejection
    process.on('unhandledRejection', (reason, promise) => {
        logger.error(`Unhandled rejection: ${reason}`);
        if (reason instanceof Error && reason.stack) {
            logger.error(`Stack: ${reason.stack}`);
        }
        logger.error(`Promise: ${promise}`);
        restoreTerminal();
        process.exit(1);
    });
    // Before exit - log why we're exiting
    process.on('beforeExit', (code) => {
        logger.warn(`Process beforeExit event fired with code: ${code}`);
        logger.warn('This should not happen if stdin is open - process may exit');
    });
    // Exit - log why we're exiting
    process.on('exit', (code) => {
        logger.warn(`Process exit event fired with code: ${code}`);
    });
    logger.debug('Terminal restore handlers attached');
}
/**
 * Unregister screen (cleanup)
 */
export function unregisterScreen() {
    screen = null;
}
//# sourceMappingURL=terminalRestore.js.map