/**
 * This file is part of the NocoBase (R) project.
 * Copyright (c) 2020-2024 NocoBase Co., Ltd.
 * Authors: NocoBase Team.
 *
 * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
 * For more information, please refer to: https://www.nocobase.com/agreement.
 */

var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var ai_chat_conversation_exports = {};
__export(ai_chat_conversation_exports, {
  createAIChatConversation: () => createAIChatConversation
});
module.exports = __toCommonJS(ai_chat_conversation_exports);
var import_lodash = __toESM(require("lodash"));
const createAIChatConversation = (ctx, sessionId) => {
  return new AIChatConversationImpl(ctx, sessionId);
};
class AIChatConversationImpl {
  constructor(ctx, sessionId) {
    this.ctx = ctx;
    this.sessionId = sessionId;
  }
  transaction;
  async withTransaction(runnable, transaction) {
    const instance = this.clone();
    if (transaction) {
      instance.transaction = transaction;
      return await runnable(instance, transaction);
    }
    return await instance.ctx.db.sequelize.transaction(async (transaction2) => {
      instance.transaction = transaction2;
      return await runnable(instance, transaction2);
    });
  }
  getSessionId() {
    return this.sessionId;
  }
  async addMessages(messages) {
    const isArray = import_lodash.default.isArray(messages);
    const messageList = isArray ? messages : [messages];
    const instances = await this.aiConversationMessagesRepo.create({
      values: messageList.map(
        (message) => ({
          messageId: String(this.snowflake()),
          sessionId: this.sessionId,
          role: message.role,
          content: message.content,
          attachments: message.attachments,
          workContext: message.workContext,
          metadata: message.metadata,
          toolCalls: message.toolCalls
        })
      ),
      transaction: this.transaction
    });
    return isArray ? instances : instances[0];
  }
  async removeMessages({ messageId }) {
    const filter = {
      sessionId: this.sessionId
    };
    if (messageId) {
      filter.messageId = {
        $gte: messageId
      };
    }
    await this.aiMessagesRepo.destroy({
      filter,
      transaction: this.transaction
    });
  }
  async getMessage(messageId) {
    return await this.aiMessagesRepo.findByTargetKey(messageId);
  }
  async listMessages(query) {
    const filter = {
      sessionId: this.sessionId
    };
    if (query == null ? void 0 : query.messageId) {
      filter.messageId = {
        $lt: query.messageId
      };
    }
    const messages = await this.aiConversationMessagesRepo.find({
      sort: ["-messageId"],
      // 改为倒序，取最新的
      limit: 50,
      // 限制最多 50 条消息
      filter
    });
    return messages.reverse();
  }
  async lastUserMessage() {
    const filter = {
      sessionId: this.sessionId,
      role: "user"
    };
    return await this.aiConversationMessagesRepo.findOne({
      sort: ["-messageId"],
      filter
    });
  }
  async getChatContext(options) {
    const {
      userMessages,
      userDecisions: decisions,
      tools,
      middleware,
      getSystemPrompt,
      formatMessages
    } = options ?? {};
    const messages = userMessages ? await (formatMessages == null ? void 0 : formatMessages(userMessages)) ?? [] : void 0;
    const systemPrompt = await (getSystemPrompt == null ? void 0 : getSystemPrompt(userMessages)) ?? "";
    const chatContext = {
      systemPrompt,
      messages,
      decisions,
      tools,
      middleware
    };
    return chatContext;
  }
  clone() {
    return new AIChatConversationImpl(this.ctx, this.sessionId);
  }
  snowflake() {
    return this.aiPlugin.snowflake.generate();
  }
  get aiConversationMessagesRepo() {
    return this.ctx.db.getRepository("aiConversations.messages", this.sessionId);
  }
  get aiMessagesRepo() {
    return this.ctx.db.getRepository("aiMessages");
  }
  get aiPlugin() {
    return this.ctx.app.pm.get("ai");
  }
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  createAIChatConversation
});
