/**
 * File-based logger for TUI - prevents stdout/stderr corruption
 *
 * Once blessed is active, ALL logs must go to file, never stdout/stderr.
 * Writing to stdout/stderr corrupts blessed's TUI output buffer.
 */
import fs from 'fs';
import path from 'path';
const LOG_PATH = process.env.TUI_LOG_PATH || path.join(process.cwd(), 'mk1.log');
let blessedActive = false;
/**
 * Mark blessed as active - from this point, all logs go to file only
 */
export function setBlessedActive(active) {
    blessedActive = active;
}
/**
 * Check if blessed is active (for logger.ts)
 */
export function isBlessedActive() {
    return blessedActive;
}
// Keep file descriptor open for faster writes
let logFd = null;
/**
 * Initialize log file descriptor (call once at startup)
 */
function initLogFile() {
    try {
        // Open file in append mode and keep it open
        logFd = fs.openSync(LOG_PATH, 'a');
    }
    catch (error) {
        // If open fails, try to create parent directory
        try {
            const logDir = path.dirname(LOG_PATH);
            if (!fs.existsSync(logDir)) {
                fs.mkdirSync(logDir, { recursive: true });
            }
            logFd = fs.openSync(LOG_PATH, 'a');
        }
        catch {
            // Ignore - will use appendFileSync as fallback
            logFd = null;
        }
    }
}
/**
 * Write to log file (safe during TUI)
 */
function logToFile(line) {
    try {
        if (logFd !== null) {
            // Use open file descriptor for faster writes
            fs.writeSync(logFd, line + '\n', null, 'utf8');
            // Force flush immediately
            fs.fsyncSync(logFd);
        }
        else {
            // Fallback to appendFileSync
            fs.appendFileSync(LOG_PATH, line + '\n', 'utf8');
            // Force flush by using fsync
            try {
                const fd = fs.openSync(LOG_PATH, 'a');
                fs.fsyncSync(fd);
                fs.closeSync(fd);
            }
            catch {
                // Ignore fsync errors
            }
        }
    }
    catch (error) {
        // Silently fail - don't corrupt TUI with error output
        // But try to log to stderr if blessed not active yet (shouldn't happen but safety)
        if (!blessedActive) {
            try {
                process.stderr.write(`[LOG ERROR] Failed to write to ${LOG_PATH}: ${error}\n`);
            }
            catch {
                // Ignore
            }
        }
    }
}
// Initialize log file at module load
initLogFile();
/**
 * Log message (file-only once blessed is active)
 */
function logMessage(level, message) {
    const timestamp = new Date().toISOString();
    const line = `[${timestamp}] [${level}] ${message}`;
    if (blessedActive) {
        // Once blessed is active, ONLY write to file
        logToFile(line);
    }
    else {
        // Before blessed starts, can write to stderr
        try {
            process.stderr.write(line + '\n');
        }
        catch {
            // Ignore
        }
        // Always also write to file if debug enabled
        if (process.env.TUI_DEBUG === '1') {
            logToFile(line);
        }
    }
}
export const fileLogger = {
    debug: (message) => {
        if (process.env.TUI_DEBUG === '1' || blessedActive) {
            logMessage('MK1 DEBUG', message);
        }
    },
    info: (message) => logMessage('MK1 INFO', message),
    warn: (message) => logMessage('MK1 WARN', message),
    error: (message) => logMessage('MK1 ERROR', message),
    getLogPath: () => LOG_PATH,
    // Force log to file even in debug mode (for critical startup logs)
    force: (message) => logMessage('MK1 FORCE', message),
};
//# sourceMappingURL=log.js.map