/**
 * MK1 Logger - stderr/file only, NEVER stdout
 *
 * Rules:
 * - Before blessed starts: can write to stderr
 * - After blessed starts: ONLY file (no stderr - it corrupts TUI)
 * - Never use console.log
 * - Rate-limited to prevent spam
 */
import * as fs from 'fs';
import * as path from 'path';
import * as os from 'os';
import { isBlessedActive } from './log.js';
const LOG_FILE = path.join(os.tmpdir(), '4runr_tui_mk1.log');
const MAX_LOG_SIZE = 1024 * 1024; // 1MB max log file
// Rate limiting
let lastLogTime = 0;
let logCount = 0;
const RATE_LIMIT_MS = 100; // Max 1 log per 100ms
const RATE_LIMIT_BURST = 10; // Allow 10 logs in burst
/**
 * Write to log file (with rotation)
 */
function writeToFile(level, message) {
    try {
        // Check file size and rotate if needed
        if (fs.existsSync(LOG_FILE)) {
            const stats = fs.statSync(LOG_FILE);
            if (stats.size > MAX_LOG_SIZE) {
                // Rotate: move to .old
                const oldFile = LOG_FILE + '.old';
                if (fs.existsSync(oldFile)) {
                    fs.unlinkSync(oldFile);
                }
                fs.renameSync(LOG_FILE, oldFile);
            }
        }
        const timestamp = new Date().toISOString();
        const logLine = `[${timestamp}] [${level}] ${message}\n`;
        fs.appendFileSync(LOG_FILE, logLine, 'utf8');
    }
    catch (error) {
        // If file write fails, silently ignore (we don't want to break the TUI)
    }
}
/**
 * Rate-limited log writer
 */
function rateLimitedLog(level, message) {
    const now = Date.now();
    // Reset counter if enough time has passed
    if (now - lastLogTime > RATE_LIMIT_MS) {
        logCount = 0;
    }
    // Check rate limit
    if (logCount >= RATE_LIMIT_BURST && (now - lastLogTime) < RATE_LIMIT_MS) {
        // Rate limited - skip this log
        return;
    }
    logCount++;
    lastLogTime = now;
    // CRITICAL: Once blessed is active, NEVER write to stderr (corrupts TUI)
    // Only write to file
    if (isBlessedActive()) {
        // Blessed is active - only write to file
        writeToFile(level, message);
    }
    else {
        // Before blessed starts - can write to stderr
        try {
            process.stderr.write(`[MK1 ${level}] ${message}\n`);
        }
        catch {
            // Ignore stderr errors
        }
        // Also write to file if debug enabled
        if (process.env.TUI_DEBUG === '1') {
            writeToFile(level, message);
        }
    }
}
export const logger = {
    info: (message) => rateLimitedLog('INFO', message),
    warn: (message) => rateLimitedLog('WARN', message),
    error: (message) => rateLimitedLog('ERROR', message),
    debug: (message) => {
        if (process.env.TUI_DEBUG === '1') {
            rateLimitedLog('DEBUG', message);
        }
    },
    /**
     * Get log file path
     */
    getLogFile: () => LOG_FILE,
};
//# sourceMappingURL=logger.js.map