import { mkdirSync } from "node:fs";
import { join } from "node:path";
import pino from "pino";
import { getLogDir } from "./paths.js";
const VALID_LEVELS = new Set(["debug", "info", "warn", "error", "fatal", "trace"]);
function resolveLevel() {
    const env = process.env.LOG_LEVEL?.toLowerCase();
    if (env && VALID_LEVELS.has(env)) {
        // Map trace/fatal to closest supported level
        if (env === "trace")
            return "debug";
        if (env === "fatal")
            return "error";
        return env;
    }
    return "info";
}
function buildTransports() {
    const targets = [];
    // File transport with daily rotation
    const logDir = getLogDir();
    try {
        mkdirSync(logDir, { recursive: true });
    }
    catch {
        // Best effort - directory may already exist
    }
    targets.push({
        target: "pino-roll",
        options: {
            file: join(logDir, "daemon.log"),
            frequency: "daily",
            limit: { count: 7 },
            mkdir: true,
        },
        level: "debug",
    });
    // Console transport: pretty in dev, JSON otherwise
    const isDev = process.env.NODE_ENV !== "production";
    if (isDev) {
        targets.push({
            target: "pino-pretty",
            options: {
                colorize: true,
                translateTime: "SYS:yyyy-mm-dd HH:MM:ss.l",
                ignore: "pid,hostname",
            },
            level: "debug",
        });
    }
    else {
        targets.push({
            target: "pino/file",
            options: { destination: 1 }, // stdout
            level: "debug",
        });
    }
    return { targets };
}
let pinoInstance;
function getInstance() {
    if (!pinoInstance) {
        pinoInstance = pino({
            level: resolveLevel(),
            transport: buildTransports(),
        });
    }
    return pinoInstance;
}
/**
 * Create a child logger with request context.
 * Use this in request handlers to include requestId for tracing.
 */
export function createRequestLogger(requestId) {
    const child = getInstance().child({ requestId });
    return {
        debug: (message) => child.debug(message),
        info: (message) => child.info(message),
        warn: (message) => child.warn(message),
        error: (message) => child.error(message),
        child: (bindings) => child.child(bindings),
    };
}
export const logger = {
    debug(message) {
        getInstance().debug(message);
    },
    info(message) {
        getInstance().info(message);
    },
    warn(message) {
        getInstance().warn(message);
    },
    error(message) {
        getInstance().error(message);
    },
    /**
     * Create a child logger with additional bound context.
     */
    child(bindings) {
        return getInstance().child(bindings);
    },
};
//# sourceMappingURL=logger.js.map