/**
 * 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 aiEmployees_exports = {};
__export(aiEmployees_exports, {
  getTemplates: () => getTemplates,
  list: () => list,
  listByUser: () => listByUser,
  updateUserPrompt: () => updateUserPrompt
});
module.exports = __toCommonJS(aiEmployees_exports);
var import_actions = __toESM(require("@nocobase/actions"));
var templates = __toESM(require("../ai-employees/templates"));
var import_lodash = __toESM(require("lodash"));
var import_ai_feature_manager = require("../manager/ai-feature-manager");
const list = async (ctx, next) => {
  var _a, _b;
  const { paginate } = ctx.action.params || {};
  const plugin = ctx.app.pm.get("ai");
  const builtInManager = plugin.builtInManager;
  await import_actions.default.list(ctx, () => {
  });
  const locale = ctx.getCurrentLocale();
  let data;
  if (paginate === "false" || paginate === false) {
    ctx.body = ctx.body.map((it) => it.toJSON());
    data = ctx.body;
  } else {
    ctx.body.rows = ctx.body.rows.map((it) => it.toJSON());
    data = ctx.body.rows;
  }
  const featureEnabled = plugin.features.isFeaturesEnabled(Object.values(import_ai_feature_manager.EEFeatures));
  if (featureEnabled) {
    const knowledgeBaseKeys = import_lodash.default.uniq(
      data.map((it) => {
        var _a2;
        return ((_a2 = it.knowledgeBase) == null ? void 0 : _a2.knowledgeBaseKeys) ?? [];
      }).flatMap((it) => it)
    );
    const knowledgeBaseList = await plugin.features.knowledgeBase.getKnowledgeBase(knowledgeBaseKeys);
    const existedKnowledgeBaseKeys = (knowledgeBaseList == null ? void 0 : knowledgeBaseList.map((it) => it.key)) ?? [];
    for (const row of data) {
      row.missingKnowledgeBaseKeys = [];
      if (!((_b = (_a = row.knowledgeBase) == null ? void 0 : _a.knowledgeBaseKeys) == null ? void 0 : _b.length)) {
        continue;
      }
      for (const k of row.knowledgeBase.knowledgeBaseKeys) {
        if (existedKnowledgeBaseKeys.includes(k)) {
          continue;
        }
        row.missingKnowledgeBaseKeys.push(k);
      }
    }
  }
  data.forEach((row) => {
    if (row.builtIn) {
      builtInManager.setupBuiltInInfo(locale, row);
    }
  });
  await next();
};
const listByUser = async (ctx, next) => {
  const plugin = ctx.app.pm.get("ai");
  const tools = await plugin.ai.toolsManager.listTools({ scope: "GENERAL" });
  const user = ctx.auth.user;
  const model = ctx.db.getModel("aiEmployees");
  const sequelize = ctx.db.sequelize;
  const roles = ctx.state.currentRoles;
  const builtInManager = plugin.builtInManager;
  let where = {
    enabled: true
  };
  if (!(roles == null ? void 0 : roles.includes("root"))) {
    const aiEmployees = await ctx.db.getRepository("rolesAiEmployees").find({
      filter: {
        roleName: ctx.state.currentRoles
      }
    });
    if (!aiEmployees) {
      ctx.body = [];
      return next();
    }
    where = {
      ...where,
      username: aiEmployees.map((item) => item.aiEmployee)
    };
  }
  const rows = await model.findAll({
    where,
    include: [
      {
        model: ctx.db.getModel("usersAiEmployees"),
        as: "userConfigs",
        required: false,
        where: { userId: user.id }
      }
    ],
    order: [
      [
        sequelize.literal(
          `CASE WHEN ${sequelize.getQueryInterface().quoteIdentifiers("userConfigs.sort")} IS NOT NULL THEN 0 ELSE 1 END`
        ),
        "ASC"
      ],
      [sequelize.fn("COALESCE", sequelize.col("userConfigs.sort"), sequelize.col("aiEmployees.sort")), "ASC"]
    ]
  });
  const locale = ctx.getCurrentLocale();
  rows.forEach((row) => {
    if (row.builtIn) {
      builtInManager.setupBuiltInInfo(locale, row);
    }
  });
  ctx.body = rows.map((row) => {
    var _a, _b;
    const skillSettings = row.skillSettings ?? { skills: [] };
    if (!import_lodash.default.isArray(skillSettings.skills)) {
      skillSettings.skills = [];
    }
    for (const tool of tools) {
      skillSettings.skills.push({
        name: tool.definition.name,
        auto: tool.defaultPermission === "ALLOW"
      });
    }
    return {
      username: row.username,
      nickname: row.nickname,
      position: row.position,
      avatar: row.avatar,
      bio: row.bio,
      greeting: row.greeting,
      userConfig: {
        prompt: (_b = (_a = row.userConfigs) == null ? void 0 : _a[0]) == null ? void 0 : _b.prompt
      },
      skillSettings,
      builtIn: row.builtIn,
      category: row.category
    };
  });
  await next();
};
const updateUserPrompt = async (ctx, next) => {
  const { aiEmployee, prompt } = ctx.action.params.values || {};
  if (!aiEmployee) {
    ctx.throw(400);
  }
  const user = ctx.auth.user;
  const repo = ctx.db.getRepository("usersAiEmployees");
  const record = await repo.findOne({
    filter: {
      userId: user.id,
      aiEmployee
    }
  });
  if (record) {
    await record.update({
      prompt
    });
    return next();
  }
  await repo.create({
    values: {
      aiEmployee,
      userId: user.id,
      prompt,
      sort: null
    }
  });
  await next();
};
const getTemplates = async (ctx, next) => {
  const locale = ctx.getCurrentLocale() || "en-US";
  ctx.body = Object.values(templates).map((template) => template[locale]);
  await next();
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  getTemplates,
  list,
  listByUser,
  updateUserPrompt
});
