"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.redirectLogsToStderr = exports.createLogger = exports.setLogLevel = exports.registerErrorCapture = void 0;
const loglevel_1 = __importDefault(require("loglevel"));
// Log levels: TRACE, DEBUG, INFO, WARN, ERROR, SILENT
const LOG_LEVEL = (process.env.LOG_LEVEL || 'INFO').toUpperCase();
// Callback invoked on every log.error() call so that errors are forwarded to
// PostHog as structured events. This lets us catch production errors surfaced
// through the logger without requiring a separate log aggregation pipeline.
// Registered by TelemetryService when it initializes; no-ops until then.
let _onError = null;
const registerErrorCapture = (fn) => {
    _onError = fn;
};
exports.registerErrorCapture = registerErrorCapture;
// Configure loglevel
loglevel_1.default.setLevel(loglevel_1.default.levels[LOG_LEVEL] || loglevel_1.default.levels.INFO);
// Add emojis and better formatting for development
if (process.env.NODE_ENV !== 'production') {
    const originalFactory = loglevel_1.default.methodFactory;
    loglevel_1.default.methodFactory = (methodName, logLevel, loggerName) => {
        const rawMethod = originalFactory(methodName, logLevel, loggerName);
        const emojis = {
            trace: '🔍',
            debug: '🐛',
            info: '📋',
            warn: '⚠️',
            error: '❌',
        };
        return (message, ...args) => {
            const emoji = emojis[methodName] || '';
            const timestamp = new Date().toISOString();
            rawMethod(`${emoji} [${timestamp}] ${message}`, ...args);
        };
    };
    loglevel_1.default.setLevel(loglevel_1.default.getLevel()); // Trigger rebuild
}
// Function to update log level dynamically
const setLogLevel = (level) => {
    const LOG_LEVEL = level.toUpperCase();
    loglevel_1.default.setLevel(loglevel_1.default.levels[LOG_LEVEL] || loglevel_1.default.levels.INFO);
};
exports.setLogLevel = setLogLevel;
// Create service-specific logger factory
const createLogger = (serviceName) => {
    const prefix = serviceName ? `[${serviceName}] ` : '';
    return {
        trace: (message, ...args) => loglevel_1.default.trace(`${prefix}${message}`, ...args),
        debug: (message, ...args) => loglevel_1.default.debug(`${prefix}${message}`, ...args),
        info: (message, ...args) => loglevel_1.default.info(`${prefix}${message}`, ...args),
        warn: (message, ...args) => loglevel_1.default.warn(`${prefix}${message}`, ...args),
        error: (message, ...args) => {
            loglevel_1.default.error(`${prefix}${message}`, ...args);
            try {
                _onError?.(message, args, serviceName);
            }
            catch (e) {
                // Use stderr directly — cannot use log here (infinite recursion risk).
                process.stderr.write(`[logger] _onError callback threw: ${e}\n`);
            }
        },
        // Project-specific logging
        project: (projectId, message, ...args) => loglevel_1.default.info(`${prefix}[${projectId}] ${message}`, ...args),
        // API request logging
        api: (method, url, message, ...args) => loglevel_1.default.info(`${prefix}${method} ${url} - ${message}`, ...args),
    };
};
exports.createLogger = createLogger;
/**
 * Redirect all log output to stderr.
 * Required for MCP mode where stdout is reserved for the MCP protocol stream.
 */
const redirectLogsToStderr = () => {
    loglevel_1.default.methodFactory = (_methodName, _logLevel, _loggerName) => {
        return (message, ...args) => {
            const formatted = args.length > 0 ? `${message} ${args.map(String).join(' ')}` : message;
            process.stderr.write(formatted + '\n');
        };
    };
    loglevel_1.default.setLevel(loglevel_1.default.getLevel()); // Trigger rebuild
};
exports.redirectLogsToStderr = redirectLogsToStderr;
// Default logger (no service prefix) - used internally
//# sourceMappingURL=logger.js.map