import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
import { format } from "node:util";
const STARTUP_TIME = new Date();
const DISABLE_FILE_LOG_VALUES = new Set(["0", "false", "off", "no"]);
const MAX_BUFFERED_NODE_LOGS = 200;
let startupLogFilePath;
let nodeLogSink = null;
const bufferedNodeLogs = [];
function pad(value, length = 2) {
    return String(value).padStart(length, "0");
}
export function formatStartupTimestamp(date) {
    return [
        date.getFullYear(),
        pad(date.getMonth() + 1),
        pad(date.getDate()),
        "-",
        pad(date.getHours()),
        pad(date.getMinutes()),
        pad(date.getSeconds()),
        "-",
        pad(date.getMilliseconds(), 3),
    ].join("");
}
export function getStartupPathName(startupPath) {
    const normalized = String(startupPath || "").trim().replace(/[\\/]+$/, "");
    if (!normalized) {
        return "workspace";
    }
    const parts = normalized.split(/[\\/]+/).filter(Boolean);
    return parts[parts.length - 1] || "workspace";
}
export function sanitizeLogFileNameSegment(segment) {
    const controlCharactersPattern = new RegExp(`[${String.fromCharCode(0)}-${String.fromCharCode(31)}]`, "g");
    const sanitized = segment
        .replace(/[<>:"/\\|?*]/g, "_")
        .replace(controlCharactersPattern, "_")
        .replace(/\s+/g, " ")
        .trim()
        .replace(/[. ]+$/g, "");
    return sanitized || "workspace";
}
export function buildStartupLogFilePath(options = {}) {
    const logDir = options.logDir || path.join(options.homeDir || os.homedir(), ".aws-bridge", "log");
    const startupPathName = sanitizeLogFileNameSegment(getStartupPathName(options.startupPath || process.env.AWS_WORKSPACE_PATH || process.cwd()));
    const startupTime = formatStartupTimestamp(options.startupTime || STARTUP_TIME);
    return path.join(logDir, `${startupPathName}-${startupTime}.log`);
}
export function initializeStartupLogFile() {
    if (startupLogFilePath !== undefined) {
        return startupLogFilePath;
    }
    const fileLogSwitch = String(process.env.AWS_MCP_FILE_LOG || "").trim().toLowerCase();
    if (DISABLE_FILE_LOG_VALUES.has(fileLogSwitch)) {
        startupLogFilePath = null;
        return null;
    }
    try {
        startupLogFilePath = buildStartupLogFilePath({
            logDir: process.env.AWS_MCP_LOG_DIR || undefined,
        });
        fs.mkdirSync(path.dirname(startupLogFilePath), { recursive: true });
        return startupLogFilePath;
    }
    catch (error) {
        startupLogFilePath = null;
        console.warn("[Logger] 无法创建 MCP 启动日志文件:", error);
        return null;
    }
}
function writeFileLog(level, args) {
    if (startupLogFilePath === undefined) {
        return;
    }
    const logFilePath = startupLogFilePath;
    if (!logFilePath) {
        return;
    }
    const line = `${new Date().toISOString()} [${level.toUpperCase()}] ${format(...args)}\n`;
    try {
        fs.appendFileSync(logFilePath, line, "utf8");
    }
    catch (error) {
        startupLogFilePath = null;
        console.warn("[Logger] 无法写入 MCP 启动日志文件:", error);
    }
}
function output(level, args) {
    const entry = {
        level,
        message: format(...args),
        timestamp: new Date().toISOString(),
    };
    switch (level) {
        case "info":
            console.error(...args);
            break;
        case "warn":
            console.warn(...args);
            break;
        case "error":
            console.error(...args);
            break;
    }
    writeFileLog(level, args);
    emitNodeLog(entry);
}
/**
 * 绑定 MCP Node.js 日志上报通道。
 * 主流程：设置实时 sink -> 回放启动以来的缓冲日志 -> 后续日志实时推送。
 */
export function setMcpNodeLogSink(sink) {
    nodeLogSink = sink;
    if (!sink) {
        return;
    }
    for (const entry of bufferedNodeLogs) {
        sink(entry);
    }
}
function emitNodeLog(entry) {
    bufferedNodeLogs.push(entry);
    if (bufferedNodeLogs.length > MAX_BUFFERED_NODE_LOGS) {
        bufferedNodeLogs.splice(0, bufferedNodeLogs.length - MAX_BUFFERED_NODE_LOGS);
    }
    if (nodeLogSink) {
        nodeLogSink(entry);
    }
}
export const logger = {
    info: (...args) => output("info", args),
    warn: (...args) => output("warn", args),
    error: (...args) => output("error", args),
};
//# sourceMappingURL=logger.js.map