"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Logger = void 0;
const log4js_1 = __importDefault(require("log4js"));
const node_os_1 = require("node:os");
const node_path_1 = require("node:path");
const node_fs_1 = require("node:fs");
const clack = __importStar(require("@clack/prompts"));
const colors_1 = require("./colors");
class Logger {
    static inited;
    logger;
    static timestamp = new Date().toISOString().replace(/[:.]/g, "-");
    static logFileName = `cli-${Logger.timestamp}.log`;
    static logDir = (0, node_path_1.join)((0, node_os_1.tmpdir)(), "@interopio-iocd-cli");
    static logPath = (0, node_path_1.join)(Logger.logDir, Logger.logFileName);
    constructor(name) {
        this.logger = log4js_1.default.getLogger(name);
    }
    printLogLocation() {
        this.logger.info(`Log file: ${Logger.logPath}`);
    }
    static getInstance(name) {
        if (!Logger.inited) {
            this.setupLogging();
            Logger.inited = true;
        }
        return new Logger(name);
    }
    static setupLogging() {
        // Ensure log directory exists
        (0, node_fs_1.mkdirSync)(Logger.logDir, { recursive: true });
        const customAppender = {
            configure: () => {
                // let spinner = false;
                return (loggingEvent) => {
                    if (loggingEvent.level.level < 20000) {
                        return;
                    }
                    const fullMessage = loggingEvent.data
                        .map(d => {
                        // check if error and format properly to string
                        if (d instanceof Error) {
                            return d.stack || d.message;
                        }
                        if (d.stack || d.message) {
                            return d.stack || d.message;
                        }
                        if (typeof d === "string") {
                            return d;
                        }
                        return JSON.stringify(d, null, 4);
                    })
                        .join(" ");
                    // check if level is error user error
                    if (loggingEvent.level.level >= 40000) {
                        clack.log.error(fullMessage);
                        return;
                    }
                    if (loggingEvent.level.level >= 30000) {
                        clack.log.warn(fullMessage);
                        return;
                    }
                    // some extra rules for info level
                    const firstMessage = loggingEvent.data[0];
                    const firstWord = firstMessage.split(" ")[0];
                    if (firstMessage.toLowerCase().includes("successfully")) {
                        clack.log.success((0, colors_1.green)(fullMessage));
                    }
                    else if (firstWord.endsWith("ing")) {
                        clack.log.step(fullMessage);
                    }
                    else if (firstMessage.toLowerCase().includes("failed")) {
                        clack.log.error(fullMessage);
                    }
                    else {
                        clack.log.info(fullMessage);
                    }
                };
            },
        };
        const appenders = {
            "console-info": {
                type: customAppender,
                appender: "console",
                level: "info",
            },
            file: {
                type: "file",
                filename: Logger.logPath,
                maxLogSize: 10485760, // 10MB in bytes
                layout: {
                    type: "pattern",
                    pattern: "[%d] [%p] %c - %m",
                },
            },
        };
        const categories = {
            default: {
                appenders: ["console-info", "file"],
                level: "debug",
            },
        };
        log4js_1.default.configure({
            appenders,
            categories,
        });
    }
    info(message, ...args) {
        this.logger.info(message, ...args);
    }
    debug(message, ...args) {
        this.logger.debug(message, ...args);
    }
    warn(message, ...args) {
        this.logger.warn(message, ...args);
    }
    error(message, ...args) {
        this.logger.error(message, ...args);
    }
    flush() {
        // Force log4js to flush all buffers by calling shutdown
        // This ensures all pending log writes are completed
        log4js_1.default.shutdown();
    }
    getLogPath() {
        return Logger.logPath;
    }
    setVerbose(verbose) {
        if (verbose) {
            this.logger.level = "debug";
        }
        else {
            this.logger.level = "info";
        }
    }
    shutdown() {
        log4js_1.default.shutdown();
    }
}
exports.Logger = Logger;
//# sourceMappingURL=logger.js.map