/**
 * 统一日志模块
 *
 * 提供结构化日志输出，支持不同日志级别和格式化
 */
const LOG_LEVEL_PRIORITY = {
    debug: 0,
    info: 1,
    warn: 2,
    error: 3,
};
/**
 * 格式化时间戳
 */
function formatTimestamp() {
    return new Date().toISOString();
}
/**
 * 格式化日志参数
 */
function formatArgs(args) {
    return args
        .map((arg) => {
        if (typeof arg === 'object' && arg !== null) {
            try {
                return JSON.stringify(arg, null, 2);
            }
            catch {
                return String(arg);
            }
        }
        return String(arg);
    })
        .join(' ');
}
/**
 * 日志器类
 */
export class Logger {
    constructor(config = { level: 'info' }) {
        this.level = config.level;
        this.prefix = config.prefix || '';
        this.timestamp = config.timestamp ?? true;
    }
    shouldLog(level) {
        return LOG_LEVEL_PRIORITY[level] >= LOG_LEVEL_PRIORITY[this.level];
    }
    formatMessage(level, args) {
        const parts = [];
        if (this.timestamp) {
            parts.push(`[${formatTimestamp()}]`);
        }
        parts.push(`[${level.toUpperCase()}]`);
        if (this.prefix) {
            parts.push(`[${this.prefix}]`);
        }
        parts.push(formatArgs(args));
        return parts.join(' ');
    }
    debug(...args) {
        if (this.shouldLog('debug')) {
            console.debug(this.formatMessage('debug', args));
        }
    }
    info(...args) {
        if (this.shouldLog('info')) {
            console.info(this.formatMessage('info', args));
        }
    }
    warn(...args) {
        if (this.shouldLog('warn')) {
            console.warn(this.formatMessage('warn', args));
        }
    }
    error(...args) {
        if (this.shouldLog('error')) {
            console.error(this.formatMessage('error', args));
        }
    }
    /**
     * 创建子日志器
     */
    child(prefix) {
        return new Logger({
            level: this.level,
            prefix: this.prefix ? `${this.prefix}:${prefix}` : prefix,
            timestamp: this.timestamp,
        });
    }
}
// 默认日志器实例
const defaultLogger = new Logger({
    level: process.env.LOG_LEVEL || 'info',
});
// 导出便捷方法
export const logger = {
    debug: (...args) => defaultLogger.debug(...args),
    info: (...args) => defaultLogger.info(...args),
    warn: (...args) => defaultLogger.warn(...args),
    error: (...args) => defaultLogger.error(...args),
    child: (prefix) => defaultLogger.child(prefix),
};
// 创建带前缀的日志器
export function createLogger(prefix, config) {
    return new Logger({
        level: config?.level || process.env.LOG_LEVEL || 'info',
        prefix,
        timestamp: config?.timestamp,
    });
}
