// @ts-nocheck

export function createRuntimeLogging({ windowRef, runtimeUniqueId }) {
  const editorLogEntries = [];
  const EDITOR_LOG_LIMIT = 500;
  let statusLogWindowController = null;

  function formatEditorLogTimestamp(timestamp) {
    try {
      return new Date(timestamp).toLocaleString();
    } catch {
      return String(timestamp || "");
    }
  }

  function appendEditorLogEntry(level, message) {
    const normalizedMessage = String(message || "").trim();
    if (!normalizedMessage) {
      return null;
    }
    const timestamp = Date.now();
    const entry = {
      id: runtimeUniqueId(),
      timestamp,
      timestampLabel: formatEditorLogTimestamp(timestamp),
      level: String(level || "Information").trim() || "Information",
      message: normalizedMessage,
    };
    editorLogEntries.push(entry);
    while (editorLogEntries.length > EDITOR_LOG_LIMIT) {
      editorLogEntries.shift();
    }
    statusLogWindowController?.refresh?.();
    return entry;
  }

  function getEditorLogEntries() {
    return editorLogEntries.slice();
  }

  function clearEditorLogEntries() {
    editorLogEntries.splice(0, editorLogEntries.length);
    statusLogWindowController?.refresh?.();
  }

  windowRef.addEventListener("error", (event) => {
    const message = String(event?.message || event?.error?.message || "Unknown runtime error");
    appendEditorLogEntry("Error", message);
  });

  windowRef.addEventListener("unhandledrejection", (event) => {
    const reason = event?.reason;
    const message = typeof reason === "string"
      ? reason
      : String(reason?.message || reason || "Unhandled promise rejection");
    appendEditorLogEntry("Error", message);
  });

  return {
    appendEditorLogEntry,
    getEditorLogEntries,
    clearEditorLogEntries,
    setStatusLogWindowController(nextController) {
      statusLogWindowController = nextController;
    },
  };
}
