import { EventEmitter } from "node:events";
import { appendFileSync, existsSync, mkdirSync } from "node:fs";
import { join } from "node:path";
const TOOL_CALLS_LOG = "tool-calls.jsonl";
const MAX_LOG_LINES = 500;
function getToolCallsLogPath(mapxDir) {
  return join(mapxDir, TOOL_CALLS_LOG);
}
class UiEventBus extends EventEmitter {
  static instance = null;
  mapxDir = null;
  static getInstance() {
    if (!UiEventBus.instance) {
      UiEventBus.instance = new UiEventBus();
    }
    return UiEventBus.instance;
  }
  /**
   * Set the .mapx directory so tool calls can be persisted to disk.
   * Must be called once after the project directory is known.
   */
  setMapxDir(dir) {
    this.mapxDir = join(dir, ".mapx");
    if (!existsSync(this.mapxDir)) {
      mkdirSync(this.mapxDir, { recursive: true });
    }
  }
  emitToolCall(event) {
    this.emit("tool-call", event);
    if (this.mapxDir) {
      try {
        const logPath = getToolCallsLogPath(this.mapxDir);
        appendFileSync(logPath, JSON.stringify(event) + "\n", "utf-8");
        this.trimLogIfNeeded(logPath);
      } catch {
      }
    }
  }
  emitScanProgress(event) {
    this.emit("scan-progress", event);
  }
  emitScanComplete(event) {
    this.emit("scan-complete", event);
  }
  trimLogIfNeeded(logPath) {
    try {
      const { readFileSync, writeFileSync } = require("node:fs");
      const content = readFileSync(logPath, "utf-8");
      const lines = content.split("\n").filter(Boolean);
      if (lines.length > MAX_LOG_LINES) {
        const trimmed = lines.slice(-MAX_LOG_LINES);
        writeFileSync(logPath, trimmed.join("\n") + "\n", "utf-8");
      }
    } catch {
    }
  }
}
export {
  UiEventBus,
  getToolCallsLogPath
};
