/**
 * MK1 Stdout Guard - Block stdout writes unless explicitly allowed
 *
 * Critical: Prevents "weird symbols / box drawing dumped to console" issue
 *
 * Rules:
 * - By default, block process.stdout.write
 * - Allow only if TUI_ALLOW_STDOUT=1
 * - When blocked, redirect to logger.debug() (rate-limited)
 */
import { logger } from './logger.js';
let stdoutGuardEnabled = false;
let originalStdoutWrite;
/**
 * Enable stdout guard
 * Call this BEFORE creating the screen
 */
export function enableStdoutGuard() {
    if (stdoutGuardEnabled) {
        return; // Already enabled
    }
    stdoutGuardEnabled = true;
    originalStdoutWrite = process.stdout.write.bind(process.stdout);
    // Wrap stdout.write
    process.stdout.write = function (chunk, encoding, callback) {
        // Check if stdout is explicitly allowed
        if (process.env.TUI_ALLOW_STDOUT === '1') {
            return originalStdoutWrite(chunk, encoding, callback);
        }
        // CRITICAL: Allow blessed's output through (it needs to write escape sequences)
        // Check if this is from blessed by looking at the stack trace
        const stack = new Error().stack || '';
        if (stack.includes('blessed') || stack.includes('neo-blessed') || stack.includes('program.js')) {
            // This is from blessed - allow it through
            return originalStdoutWrite(chunk, encoding, callback);
        }
        // Block stdout - redirect to logger
        const str = typeof chunk === 'string' ? chunk : chunk.toString();
        const lines = str.split('\n');
        for (const line of lines) {
            if (line.trim()) {
                logger.debug(`BLOCKED stdout: ${line.substring(0, 100)}`);
            }
        }
        // Return success to prevent errors, but don't actually write
        if (callback) {
            callback();
        }
        return true;
    };
    logger.debug('Stdout guard enabled');
}
/**
 * Disable stdout guard
 * Call this on exit/cleanup
 */
export function disableStdoutGuard() {
    if (!stdoutGuardEnabled) {
        return;
    }
    if (originalStdoutWrite) {
        process.stdout.write = originalStdoutWrite;
    }
    stdoutGuardEnabled = false;
    logger.debug('Stdout guard disabled');
}
/**
 * Check if guard is enabled
 */
export function isStdoutGuardEnabled() {
    return stdoutGuardEnabled;
}
//# sourceMappingURL=stdoutGuard.js.map