/**
 * MK2 Kernel - Screen initialization and lifecycle management
 *
 * MK2 Phase 1: Frame Lock
 * - Clean screen initialization
 * - Lifecycle management
 * - No command logic, no adapters, no AI features
 */
import blessed from 'neo-blessed';
import { restoreTerminal } from './terminalRestore.js';
import { enableStdoutGuard, disableStdoutGuard } from './stdoutGuard.js';
export class MK2Kernel {
    screen = null;
    /**
     * Get the screen instance
     */
    getScreen() {
        return this.screen;
    }
    /**
     * Start kernel - initialize screen
     */
    async start(renderFn, options = {}) {
        process.stderr.write('[DEBUG] Kernel.start: entry\n');
        // Enforce singleton: destroy old screen if exists
        if (globalThis.__MK2_SCREEN__) {
            try {
                globalThis.__MK2_SCREEN__.destroy();
            }
            catch {
                // Ignore
            }
            globalThis.__MK2_SCREEN__ = undefined;
        }
        process.stderr.write('[DEBUG] Kernel.start: enabling stdout guard\n');
        // Enable stdout guard BEFORE creating screen
        enableStdoutGuard();
        process.stderr.write('[DEBUG] Kernel.start: stdout guard enabled\n');
        // Ensure stdin is a TTY
        process.stderr.write('[DEBUG] Kernel.start: checking stdin.isTTY\n');
        if (!process.stdin.isTTY) {
            throw new Error('stdin is not a TTY. Cannot start TUI.');
        }
        process.stderr.write('[DEBUG] Kernel.start: setting up stdin\n');
        // CRITICAL FIX: Ensure input is working
        process.stdin.resume();
        process.stdin.setEncoding('utf8');
        if (typeof process.stdin.setRawMode === 'function') {
            process.stdin.setRawMode(true);
        }
        process.stderr.write('[DEBUG] Kernel.start: creating blessed screen\n');
        // CRITICAL: Disable full-frame border in browser mode (prevents scrollbars)
        const { isWebTerminal } = await import('./safeViewport.js');
        const isWeb = isWebTerminal();
        // Create screen with stable options
        this.screen = blessed.screen({
            smartCSR: true,
            fullUnicode: true,
            warnings: false,
            title: '4Runr MK2',
            output: process.stdout,
            input: process.stdin,
            scrollable: false,
            alwaysScroll: false,
            fastCSR: true,
            useBCE: true,
            terminal: process.env.TERM || 'xterm-256color',
            // CRITICAL: No border in browser mode (full-frame border causes scrollbars)
            ...(isWeb ? { border: undefined } : {}),
        });
        // CRITICAL: Explicitly remove any border style in browser mode
        if (isWeb && this.screen.border) {
            this.screen.border = undefined;
        }
        process.stderr.write('[DEBUG] Kernel.start: screen created\n');
        // Store globally for singleton enforcement
        globalThis.__MK2_SCREEN__ = this.screen;
        process.stderr.write('[DEBUG] Kernel.start: setting up program\n');
        // Clear screen and prepare for rendering
        if (this.screen.program) {
            const program = this.screen.program;
            program.clear();
            program.hideCursor();
            // CRITICAL FIX: Ensure raw mode and input listening
            if (typeof program.setRawMode === 'function') {
                program.setRawMode(true);
            }
            if (typeof program.listen === 'function') {
                program.listen();
            }
            if (program.input && typeof program.input.resume === 'function') {
                program.input.resume();
            }
        }
        // FIXED: Set up resize handler - must re-evaluate dimensions and swap views
        this.screen.on('resize', () => {
            const cols = this.screen?.width || 0;
            const rows = this.screen?.height || 0;
            if (options?.onRebuild) {
                // Debounce resize to avoid too many updates
                setTimeout(() => {
                    Promise.resolve(options.onRebuild(cols, rows)).catch((err) => {
                        // Silently ignore resize errors
                    });
                }, 100);
            }
        });
        process.stderr.write('[DEBUG] Kernel.start: calling renderFn\n');
        // Initial render
        renderFn();
        process.stderr.write('[DEBUG] Kernel.start: calling screen.render\n');
        // Render screen
        this.screen.render();
        process.stderr.write('[DEBUG] Kernel.start: completed\n');
        // Screen is ready
    }
    /**
     * Stop kernel - cleanup
     */
    stop() {
        // Disable stdout guard
        disableStdoutGuard();
        if (this.screen) {
            try {
                // Show cursor before destroying
                if (this.screen.program) {
                    const program = this.screen.program;
                    if (typeof program.showCursor === 'function') {
                        program.showCursor();
                    }
                    // Disable raw mode
                    if (typeof program.setRawMode === 'function') {
                        program.setRawMode(false);
                    }
                }
                this.screen.destroy();
            }
            catch {
                // Ignore errors during cleanup
            }
            this.screen = null;
        }
        globalThis.__MK2_SCREEN__ = undefined;
        restoreTerminal();
    }
}
//# sourceMappingURL=kernel.js.map