/**
 * File-based logger that writes to ~/.shortcut/agent/logs/.
 *
 * All non-critical errors (trace uploads, background tasks, etc.) should use
 * this instead of console.error/console.warn to avoid polluting the TUI.
 */
import { appendFileSync, mkdirSync } from 'fs';
import { join } from 'path';
import { getAgentDir } from '../../config.js';
let logsDir;
function getLogsDir() {
    if (!logsDir) {
        logsDir = join(getAgentDir(), 'logs');
        mkdirSync(logsDir, { recursive: true });
    }
    return logsDir;
}
export function getAgentLogPath() {
    return join(getLogsDir(), 'agent.log');
}
function formatEntry(level, tag, message, error) {
    const ts = new Date().toISOString();
    let line = `${ts} [${level}] [${tag}] ${message}`;
    if (error instanceof Error) {
        line += `\n  ${error.message}`;
        if (error.stack)
            line += `\n${error.stack}`;
    }
    else if (error !== undefined) {
        line += `\n  ${String(error)}`;
    }
    return line + '\n';
}
function write(level, tag, message, error) {
    try {
        const entry = formatEntry(level, tag, message, error);
        appendFileSync(getAgentLogPath(), entry);
    }
    catch {
        // If we can't write logs, silently give up — never pollute the TUI
    }
}
/**
 * Intercept Node.js process warnings (e.g. DEP0190) and route them to the
 * agent log instead of stderr, preventing TUI corruption.
 * Adding a listener suppresses Node's default stderr output for warnings.
 * Returns an unsubscribe function to restore default behaviour.
 */
export function interceptProcessWarnings() {
    const listener = (warning) => {
        write('WARN', 'node', warning.message, warning);
    };
    process.on('warning', listener);
    return () => process.removeListener('warning', listener);
}
export const log = {
    error(tag, message, error) {
        write('ERROR', tag, message, error);
    },
    warn(tag, message, error) {
        write('WARN', tag, message, error);
    },
    info(tag, message) {
        write('INFO', tag, message);
    }
};
//# sourceMappingURL=agent-log.js.map