"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createLogger = void 0;
const crypto_1 = require("crypto");
const log_config_1 = require("./log-config");
const log_context_1 = require("./log-context");
const log_redaction_1 = require("./log-redaction");
const log_storage_1 = require("./log-storage");
const processRunId = `${Date.now()}-${process.pid}-${Math.random().toString(36).slice(2, 10)}`;
function createEntry(source, level, event, message, context, options = {}) {
    const config = (0, log_config_1.getResolvedLoggingConfig)();
    const reqCtx = (0, log_context_1.getRequestContext)();
    const entry = {
        id: (0, crypto_1.randomUUID)(),
        timestamp: new Date().toISOString(),
        level,
        source,
        event,
        message,
        processId: process.pid,
        runId: processRunId,
        context: config.redact ? (0, log_redaction_1.redactContext)(context) : context,
    };
    if (reqCtx?.requestId)
        entry.requestId = reqCtx.requestId;
    if (options.stage)
        entry.stage = options.stage;
    if (typeof options.latencyMs === 'number')
        entry.latencyMs = options.latencyMs;
    if (options.error)
        entry.error = options.error;
    return entry;
}
function createLogger(source, baseContext = {}) {
    const write = (level, event, message, context, extra = {}) => {
        (0, log_storage_1.appendStructuredLogEntry)(createEntry(source, level, event, message, { ...baseContext, ...(context || {}) }, extra));
    };
    return {
        child(context) {
            return createLogger(source, { ...baseContext, ...context });
        },
        debug(event, message, context) {
            write('debug', event, message, context);
        },
        info(event, message, context) {
            write('info', event, message, context);
        },
        warn(event, message, context) {
            write('warn', event, message, context);
        },
        error(event, message, context) {
            write('error', event, message, context);
        },
        stage(stage, event, message, context, options) {
            const level = options?.level ?? 'info';
            write(level, event, message, context, {
                stage,
                latencyMs: options?.latencyMs,
                error: options?.error,
            });
        },
    };
}
exports.createLogger = createLogger;
//# sourceMappingURL=logger.js.map