"use strict";
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const index = require("../_vendor/@legendapp/state/index.cjs");
const messageUtils = require("../utils/message-utils.cjs");
const core = require("../types/core.cjs");
function toStoredMessage(message) {
  const { abortController, ...stored } = message;
  return stored;
}
const messageStore$ = index.observable({
  // 已加载的消息映射表，以消息 ID 为键
  loadedMessages: {},
  // 消息 ID 的排序数组，用于保持消息顺序
  messageOrder: []
});
const messageComputed$ = {
  // 获取当前所有消息（按顺序排列）
  currentMessages: () => {
    const messageOrder = messageStore$.messageOrder.get();
    const loadedMessages = messageStore$.loadedMessages.get();
    return messageOrder.map((id) => loadedMessages[id]).filter((msg) => msg !== void 0);
  },
  // 是否应该显示欢迎界面（没有任何消息时）
  shouldShowWelcome: () => {
    return messageStore$.messageOrder.get().length === 0;
  },
  // 消息统计信息：按角色和状态分类
  messageStats: () => {
    const messages = messageStore$.loadedMessages.get();
    const messagesByRole = { user: 0, assistant: 0, system: 0 };
    const messagesByStatus = {
      [core.Status.Pending]: 0,
      [core.Status.Sending]: 0,
      [core.Status.Streaming]: 0,
      [core.Status.Completed]: 0,
      [core.Status.Failed]: 0,
      [core.Status.Cancelled]: 0
    };
    Object.values(messages).forEach((msg) => {
      messagesByRole[msg.role]++;
      if (msg.status && msg.status in messagesByStatus) {
        messagesByStatus[msg.status]++;
      }
    });
    return {
      total: Object.keys(messages).length,
      byRole: messagesByRole,
      byStatus: messagesByStatus
    };
  },
  // 根据 ID 获取单个消息
  getMessage: (messageId) => {
    return messageStore$.loadedMessages.get()[messageId];
  },
  // 检查消息是否存在
  hasMessage: (messageId) => {
    return messageId in messageStore$.loadedMessages.get();
  },
  // 获取消息的计划步骤（如果有）
  getMessagePlan: (messageId) => {
    const message = messageStore$.loadedMessages.get()[messageId];
    return message?.metadata?.planSteps || message?.metadata?.steps;
  },
  // 获取可重试的消息列表（失败且未超过最大重试次数）
  retryableMessages: () => {
    const messages = messageStore$.loadedMessages.get();
    const retryable = [];
    Object.entries(messages).forEach(([messageId, message]) => {
      if (message.status === core.Status.Failed && (message.retryCount || 0) < (message.maxRetries || 3)) {
        retryable.push(messageId);
      }
    });
    return retryable;
  }
};
const messageActions = {
  // ==== 添加操作 ====
  // 添加一条新消息（通用方法）
  addMessage: (message) => {
    const messageWithMeta = messageUtils.createEnhancedMessage(message);
    const loadedMessages = { ...messageStore$.loadedMessages.get() };
    loadedMessages[message.id] = toStoredMessage(messageWithMeta);
    messageStore$.loadedMessages.set(loadedMessages);
    const currentOrder = messageStore$.messageOrder.get();
    if (!currentOrder.includes(message.id)) {
      messageStore$.messageOrder.set([...currentOrder, message.id]);
    }
    return message.id;
  },
  // 添加用户消息
  addUserMessage: (content, attachments) => {
    const id = `user-${Date.now()}-${Math.random().toString(36).substring(7)}`;
    const message = {
      id,
      content,
      role: core.Role.User,
      attachments,
      timestamp: (/* @__PURE__ */ new Date()).toISOString(),
      status: core.Status.Completed
      // 用户消息直接标记为完成
    };
    const messageWithMeta = messageUtils.createEnhancedMessage(message);
    const loadedMessages = { ...messageStore$.loadedMessages.get() };
    if (!(messageWithMeta.id in loadedMessages)) {
      loadedMessages[messageWithMeta.id] = toStoredMessage(messageWithMeta);
      messageStore$.messageOrder.set([...messageStore$.messageOrder.get(), messageWithMeta.id]);
    }
    messageStore$.loadedMessages.set(loadedMessages);
    return id;
  },
  // 添加助手消息
  addAssistantMessage: (content) => {
    const id = `assistant-${Date.now()}-${Math.random().toString(36).substring(7)}`;
    const message = {
      id,
      content,
      role: core.Role.Assistant,
      timestamp: (/* @__PURE__ */ new Date()).toISOString(),
      status: core.Status.Completed
    };
    const messageWithMeta = messageUtils.createEnhancedMessage(message);
    const loadedMessages = { ...messageStore$.loadedMessages.get() };
    loadedMessages[messageWithMeta.id] = toStoredMessage(messageWithMeta);
    messageStore$.messageOrder.set([...messageStore$.messageOrder.get(), messageWithMeta.id]);
    messageStore$.loadedMessages.set(loadedMessages);
    return id;
  },
  // ==== 更新操作 ====
  // 更新消息内容
  updateMessage: (messageId, updates) => {
    const loadedMessages = { ...messageStore$.loadedMessages.get() };
    const existingMessage = loadedMessages[messageId];
    if (!existingMessage) {
      return;
    }
    const updatedMessage = {
      ...existingMessage,
      ...updates,
      // 特殊处理 metadata：避免完全覆盖，而是合并
      metadata: updates.metadata === void 0 ? existingMessage.metadata : updates.metadata === null ? void 0 : {
        ...existingMessage.metadata || {},
        ...updates.metadata
      },
      // 特殊处理 feedback：确保合并现有的反馈数据
      feedback: updates.feedback === void 0 ? existingMessage.feedback : updates.feedback === null ? void 0 : {
        ...existingMessage.feedback || {},
        ...updates.feedback
      }
    };
    updatedMessage.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
    if (updates.content !== void 0 && updates.content !== existingMessage.content) {
      updatedMessage.version = (existingMessage.version || 1) + 1;
    }
    loadedMessages[messageId] = toStoredMessage(updatedMessage);
    messageStore$.loadedMessages.set(loadedMessages);
  },
  // ==== 删除操作 ====
  // 删除单个消息
  removeMessage: (messageId) => {
    const loadedMessages = { ...messageStore$.loadedMessages.get() };
    delete loadedMessages[messageId];
    messageStore$.loadedMessages.set(loadedMessages);
    messageStore$.messageOrder.set(
      messageStore$.messageOrder.get().filter((id) => id !== messageId)
    );
  },
  // 替换消息（删除旧消息，添加新消息，保持位置）
  replaceMessage: (oldMessageId, newMessage) => {
    const loadedMessages = { ...messageStore$.loadedMessages.get() };
    const currentOrder = [...messageStore$.messageOrder.get()];
    delete loadedMessages[oldMessageId];
    const messageWithMeta = messageUtils.createEnhancedMessage(newMessage);
    if (messageWithMeta) {
      loadedMessages[newMessage.id] = toStoredMessage(messageWithMeta);
    }
    const oldIndex = currentOrder.indexOf(oldMessageId);
    if (oldIndex !== -1) {
      currentOrder[oldIndex] = newMessage.id;
    } else {
      currentOrder.push(newMessage.id);
    }
    messageStore$.loadedMessages.set(loadedMessages);
    messageStore$.messageOrder.set(currentOrder);
  },
  // ==== 批量操作 ====
  // 设置消息列表（完全替换）
  setMessages: (messages) => {
    const messageMap = {};
    const messageIds = [];
    messages.forEach((message) => {
      const messageWithMeta = messageUtils.createEnhancedMessage(message);
      if (messageWithMeta) {
        messageMap[message.id] = messageWithMeta;
        messageIds.push(message.id);
      }
    });
    const storedMessageMap = {};
    Object.entries(messageMap).forEach(([id, msg]) => {
      storedMessageMap[id] = toStoredMessage(msg);
    });
    messageStore$.loadedMessages.set(storedMessageMap);
    messageStore$.messageOrder.set(messageIds);
  },
  // 追加消息列表（在开头或结尾追加）
  appendMessages: (messages, position = "end") => {
    const loadedMessages = { ...messageStore$.loadedMessages.get() };
    const currentOrder = [...messageStore$.messageOrder.get()];
    const messagesToAdd = [];
    messages.forEach((message) => {
      const messageWithMeta = messageUtils.createEnhancedMessage(message);
      if (messageWithMeta) {
        loadedMessages[message.id] = toStoredMessage(messageWithMeta);
        if (!currentOrder.includes(message.id)) {
          messagesToAdd.push(message.id);
        }
      }
    });
    if (messagesToAdd.length > 0) {
      if (position === "start") {
        messageStore$.messageOrder.set([...messagesToAdd, ...currentOrder]);
      } else {
        messageStore$.messageOrder.set([...currentOrder, ...messagesToAdd]);
      }
    }
    messageStore$.loadedMessages.set(loadedMessages);
  },
  // 清空所有消息
  clearMessages: () => {
    messageStore$.loadedMessages.set({});
    messageStore$.messageOrder.set([]);
  },
  // ==== 流式传输操作 ====
  // 开始流式传输消息
  startStreamingMessage: (messageId) => {
    const existingMessage = messageStore$.loadedMessages.get()[messageId];
    if (existingMessage) {
      messageActions.updateMessage(messageId, {
        isStreaming: true,
        status: core.Status.Streaming
      });
    }
  },
  // 停止流式传输消息
  stopStreamingMessage: (messageId) => {
    const existingMessage = messageStore$.loadedMessages.get()[messageId];
    if (existingMessage) {
      messageActions.updateMessage(messageId, {
        isStreaming: false,
        status: core.Status.Completed
      });
    }
  },
  /**
   * 更新流式消息内容，处理消息类型变化时的分离逻辑
   *
   * 重要功能：当消息类型发生变化时（如从文本变为代码块），
   * 会自动创建新消息来承载新类型的内容，确保不同类型的内容分离显示
   */
  updateStreamingMessage: (messageId, content, metadata) => {
    const existingMessage = messageStore$.loadedMessages.get()[messageId];
    if (!existingMessage) {
      return {
        messageId,
        isNewMessage: false
      };
    }
    const newType = metadata?.chunkType ? messageUtils.mapChunkTypeToContentType(metadata.chunkType) : void 0;
    const currentType = existingMessage.contentType;
    const shouldCreateNewMessage = newType && currentType && newType !== currentType && existingMessage.content.length > 0;
    if (shouldCreateNewMessage) {
      const loadedMessages = { ...messageStore$.loadedMessages.get() };
      const updatedExistingMessage = {
        ...existingMessage,
        isStreaming: false
        // 注意：保持原有状态，不改为 completed，因为整体流程还在继续
      };
      loadedMessages[messageId] = toStoredMessage(updatedExistingMessage);
      const newContent = content;
      const newMessageId = `${messageId}-${Date.now()}`;
      const newMessage = {
        id: newMessageId,
        content: newContent,
        role: core.Role.Assistant,
        timestamp: (/* @__PURE__ */ new Date()).toISOString(),
        createdAt: (/* @__PURE__ */ new Date()).toISOString(),
        status: core.Status.Streaming,
        isStreaming: true,
        contentType: newType,
        version: 1,
        lastUpdatedBy: "updateStreamingMessage-new"
      };
      if (metadata?.planSteps) {
        newMessage.metadata = {
          ...newMessage.metadata,
          planSteps: metadata.planSteps
        };
      }
      loadedMessages[newMessageId] = toStoredMessage(newMessage);
      const currentOrder = [...messageStore$.messageOrder.get()];
      const oldIndex = currentOrder.indexOf(messageId);
      if (oldIndex !== -1) {
        currentOrder.splice(oldIndex + 1, 0, newMessageId);
      } else {
        currentOrder.push(newMessageId);
      }
      messageStore$.loadedMessages.set(loadedMessages);
      messageStore$.messageOrder.set(currentOrder);
      return {
        messageId: newMessageId,
        isNewMessage: true
      };
    } else {
      const updates = {
        content,
        isStreaming: true,
        status: core.Status.Streaming
      };
      if (newType && newType !== currentType) {
        updates.contentType = newType;
      }
      if (metadata?.planSteps) {
        updates.metadata = {
          ...existingMessage.metadata,
          planSteps: metadata.planSteps
        };
      }
      messageActions.updateMessage(messageId, updates);
      return {
        messageId,
        isNewMessage: false
      };
    }
  },
  /**
   * 重试失败的消息
   * 将失败消息重置为 pending 状态，并增加重试计数
   */
  retryMessage: (messageId) => {
    const message = messageStore$.loadedMessages.get()[messageId];
    if (!message) return;
    messageActions.updateMessage(messageId, {
      status: core.Status.Pending,
      retryCount: (message.retryCount || 0) + 1,
      error: void 0
      // 清除错误信息
    });
  },
  /**
   * 批量导入消息（用于历史记录加载等）
   *
   * @param messages - 要导入的消息数组
   * @param options.clearExisting - 是否清空现有消息
   * @param options.preserveOrder - 是否按时间戳保持顺序
   */
  importMessages: (messages, options) => {
    const { clearExisting = false, preserveOrder = false } = options || {};
    if (clearExisting) {
      messageStore$.loadedMessages.set({});
      messageStore$.messageOrder.set([]);
    }
    const loadedMessages = clearExisting ? {} : { ...messageStore$.loadedMessages.get() };
    const currentOrder = clearExisting ? [] : [...messageStore$.messageOrder.get()];
    messages.forEach((msg) => {
      const messageWithMeta = messageUtils.enhanceMessage(msg);
      if (!messageWithMeta) return;
      const importedMessage = {
        ...messageWithMeta,
        timestamp: msg.timestamp || messageWithMeta.timestamp,
        lastUpdatedBy: "importMessages"
      };
      loadedMessages[msg.id] = toStoredMessage(importedMessage);
      if (!currentOrder.includes(msg.id)) {
        if (preserveOrder) {
          const insertIndex = currentOrder.findIndex((id) => {
            const existingMsg = loadedMessages[id];
            return existingMsg && existingMsg.timestamp && messageWithMeta.timestamp && existingMsg.timestamp > messageWithMeta.timestamp;
          });
          if (insertIndex === -1) {
            currentOrder.push(msg.id);
          } else {
            currentOrder.splice(insertIndex, 0, msg.id);
          }
        } else {
          currentOrder.push(msg.id);
        }
      }
    });
    messageStore$.loadedMessages.set(loadedMessages);
    messageStore$.messageOrder.set(currentOrder);
  },
  /**
   * 更新所有失败消息的状态
   * 可用于批量重试或取消失败消息
   */
  updateFailedMessages: (status) => {
    const messages = messageStore$.loadedMessages.get();
    const loadedMessages = { ...messages };
    Object.entries(loadedMessages).forEach(([messageId, message]) => {
      if (message.status === core.Status.Failed) {
        loadedMessages[messageId] = {
          ...message,
          status,
          updatedAt: (/* @__PURE__ */ new Date()).toISOString()
        };
      }
    });
    messageStore$.loadedMessages.set(loadedMessages);
  },
  // ==== 额外的兼容性方法 ====
  // 重置消息（clearMessages 的别名）
  resetMessages: () => {
    messageActions.clearMessages();
  },
  // 删除单个消息（removeMessage 的别名）
  deleteMessage: (messageId) => {
    messageActions.removeMessage(messageId);
  },
  // 取消流式传输消息
  cancelStreamingMessage: (messageId) => {
    const message = messageStore$.loadedMessages.get()[messageId];
    if (message?.isStreaming) {
      messageActions.updateMessage(messageId, {
        isStreaming: false,
        status: core.Status.Cancelled
      });
    }
  },
  // 加载消息（用于分页）
  loadMessages: (messages, append = false) => {
    if (append) {
      messageActions.appendMessages(messages);
    } else {
      messageActions.setMessages(messages);
    }
  }
};
exports.messageActions = messageActions;
exports.messageComputed$ = messageComputed$;
exports.messageStore$ = messageStore$;
//# sourceMappingURL=message-store.cjs.map
