// SPDX-License-Identifier: Apache-2.0
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
import * as winston from 'winston';
import { v4 as uuidv4 } from 'uuid';
import * as util from 'node:util';
import chalk from 'chalk';
import * as constants from '../constants.js';
import { inject, injectable } from 'tsyringe-neo';
import { patchInject } from '../dependency-injection/container-helper.js';
import { InjectTokens } from '../dependency-injection/inject-tokens.js';
import { PathEx } from '../../business/utils/path-ex.js';
import { SoloError } from '../errors/solo-error.js';
const customFormat = winston.format.combine(winston.format.label({ label: 'SOLO', message: false }), winston.format.splat(), 
// include timestamp in logs
winston.format.timestamp(), winston.format.ms(), 
// add label metadata
winston.format.label({ label: '' }), 
// convert levels to upper case
winston.format(data => {
    data.level = data.level.toUpperCase();
    return data;
})(), 
// use custom format TIMESTAMP [LABEL] LEVEL: MESSAGE
winston.format.printf(data => `${data.timestamp}|${data.level}| ${data.message}`), 
// Ignore log messages if they have { private: true }
winston.format(data => (data.private ? false : data))());
let SoloWinstonLogger = class SoloWinstonLogger {
    developmentMode;
    winstonLogger;
    traceId;
    messageGroupMap = new Map();
    MINOR_LINE_SEPARATOR = '-------------------------------------------------------------------------------';
    /**
     * @param logLevel - the log level to use
     * @param developmentMode - if true, show full stack traces in error messages
     */
    constructor(logLevel, developmentMode) {
        this.developmentMode = developmentMode;
        logLevel = patchInject(logLevel, InjectTokens.LogLevel, this.constructor.name);
        this.developmentMode = patchInject(developmentMode, InjectTokens.DevelopmentMode, this.constructor.name);
        this.nextTraceId();
        this.winstonLogger = winston.createLogger({
            level: logLevel,
            format: winston.format.combine(customFormat, winston.format.json()),
            transports: [new winston.transports.File({ filename: PathEx.join(constants.SOLO_LOGS_DIR, 'solo.log') })],
        });
    }
    setDevMode(developmentMode) {
        this.debug(`dev mode logging: ${developmentMode}`);
        this.developmentMode = developmentMode;
    }
    nextTraceId() {
        this.traceId = uuidv4();
    }
    prepMeta(meta = {}) {
        meta.traceId = this.traceId;
        return meta;
    }
    showUser(message, ...arguments_) {
        console.log(util.format(message, ...arguments_));
        this.info(util.format(message, ...arguments_));
    }
    showUserError(error) {
        const stack = [{ message: error.message, stacktrace: error.stack }];
        if (error.cause) {
            let depth = 0;
            let cause = error.cause;
            while (cause !== undefined && depth < 10) {
                if (cause.stack) {
                    stack.push({ message: cause.message, stacktrace: cause.stack });
                }
                cause = cause.cause;
                depth += 1;
            }
        }
        console.log(chalk.red('*********************************** ERROR *****************************************'));
        if (this.developmentMode) {
            let prefix = '';
            let indent = '';
            for (const s of stack) {
                console.log(indent + prefix + chalk.yellow(s.message));
                // Remove everything after the first "Caused by: " and add indentation
                const formattedStacktrace = s.stacktrace
                    .replace(/Caused by:.*/s, '')
                    .replaceAll(/\n\s*/g, '\n' + indent)
                    .trim();
                console.log(indent + chalk.gray(formattedStacktrace) + '\n');
                indent += '  ';
                prefix = 'Caused by: ';
            }
        }
        else {
            const lines = error.message.split('\n');
            for (const line of lines) {
                console.log(chalk.yellow(line));
            }
        }
        console.log(chalk.red('***********************************************************************************'));
        this.error(error.message, error);
    }
    error(message, ...arguments_) {
        this.winstonLogger.error(message, ...arguments_, this.prepMeta());
    }
    warn(message, ...arguments_) {
        this.winstonLogger.warn(message, ...arguments_, this.prepMeta());
    }
    info(message, ...arguments_) {
        this.winstonLogger.info(message, ...arguments_, this.prepMeta());
    }
    debug(message, ...arguments_) {
        this.winstonLogger.debug(message, ...arguments_, this.prepMeta());
    }
    showList(title, items = []) {
        this.showUser(chalk.green(`\n *** ${title} ***`));
        this.showUser(chalk.green(this.MINOR_LINE_SEPARATOR));
        if (items.length > 0) {
            for (const name of items) {
                this.showUser(chalk.cyan(` - ${name}`));
            }
        }
        else {
            this.showUser(chalk.blue('[ None ]'));
        }
        this.showUser('\n');
        return true;
    }
    showJSON(title, object) {
        this.showUser(chalk.green(`\n *** ${title} ***`));
        this.showUser(chalk.green(this.MINOR_LINE_SEPARATOR));
        console.log(JSON.stringify(object, null, ' '));
    }
    addMessageGroup(key, title) {
        if (this.messageGroupMap.has(key)) {
            this.warn(`Message group with key "${key}" already exists. Skipping.`);
            return;
        }
        this.messageGroupMap.set(key, [`${title}:`]);
        this.debug(`Added message group "${title}" with key "${key}".`);
    }
    addMessageGroupMessage(key, message) {
        if (!this.messageGroupMap.has(key)) {
            throw new SoloError(`Message group with key "${key}" does not exist.`);
        }
        this.messageGroupMap.get(key).push(message);
        this.debug(`Added message to group "${key}": ${message}`);
    }
    showMessageGroup(key) {
        if (!this.messageGroupMap.has(key)) {
            this.warn(`Message group with key "${key}" does not exist.`);
            return;
        }
        const messages = this.messageGroupMap.get(key);
        this.showUser(chalk.green(`\n *** ${messages[0]} ***`));
        this.showUser(chalk.green(this.MINOR_LINE_SEPARATOR));
        for (let index = 1; index < messages.length; index++) {
            this.showUser(chalk.cyan(` - ${messages[index]}`));
        }
        this.showUser(chalk.green(this.MINOR_LINE_SEPARATOR));
        this.debug(`Displayed message group "${key}".`);
    }
    getMessageGroupKeys() {
        return [...this.messageGroupMap.keys()];
    }
    showAllMessageGroups() {
        const keys = this.getMessageGroupKeys();
        if (keys.length === 0) {
            this.debug('No message groups available.');
            return;
        }
        for (const key of keys) {
            this.showMessageGroup(key);
        }
    }
};
SoloWinstonLogger = __decorate([
    injectable(),
    __param(0, inject(InjectTokens.LogLevel)),
    __param(1, inject(InjectTokens.DevelopmentMode)),
    __metadata("design:paramtypes", [String, Boolean])
], SoloWinstonLogger);
export { SoloWinstonLogger };
//# sourceMappingURL=solo-winston-logger.js.map