"use strict";
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 node_path_1 = __importDefault(require("node:path"));
const node_fs_1 = require("node:fs");
const levelOrder = {
    debug: 10,
    info: 20,
    warn: 30,
    error: 40
};
class Logger {
    minLevel;
    logDir;
    fileLogging;
    logDirReady;
    constructor(level, options) {
        this.minLevel = ["debug", "info", "warn", "error"].includes(level) ? level : "info";
        this.logDir = options?.logDir ? node_path_1.default.resolve(options.logDir) : node_path_1.default.resolve(process.cwd(), "logs");
        this.fileLogging = options?.fileLogging ?? false;
        this.logDirReady = false;
    }
    debug(message, meta) {
        this.write("debug", message, meta);
    }
    info(message, meta) {
        this.write("info", message, meta);
    }
    warn(message, meta) {
        this.write("warn", message, meta);
    }
    error(message, meta) {
        this.write("error", message, meta);
    }
    write(level, message, meta) {
        if (levelOrder[level] < levelOrder[this.minLevel])
            return;
        const payload = meta ? ` ${JSON.stringify(meta)}` : "";
        const line = `[${new Date().toISOString()}] ${level.toUpperCase()} ${message}${payload}`;
        level === "error" ? console.error(line) : console.log(line);
        if (this.fileLogging) {
            void this.writeToFile(level, line);
        }
    }
    async writeToFile(level, line) {
        try {
            if (!this.logDirReady) {
                await node_fs_1.promises.mkdir(this.logDir, { recursive: true });
                this.logDirReady = true;
            }
            const date = new Date().toISOString().slice(0, 10);
            const logFile = node_path_1.default.join(this.logDir, `signals-${date}.log`);
            await node_fs_1.promises.appendFile(logFile, `${line}\n`, "utf8");
            if (level === "error") {
                const errorFile = node_path_1.default.join(this.logDir, `signals-error-${date}.log`);
                await node_fs_1.promises.appendFile(errorFile, `${line}\n`, "utf8");
            }
        }
        catch (error) {
            const message = error instanceof Error ? error.message : String(error);
            console.error(`[${new Date().toISOString()}] ERROR Failed to write log to file: ${message}`);
        }
    }
}
exports.Logger = Logger;
