/**
 * 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 tool_manager_exports = {};
__export(tool_manager_exports, {
  ToolManager: () => ToolManager
});
module.exports = __toCommonJS(tool_manager_exports);
var import_utils = require("@nocobase/utils");
var import_zod = require("zod");
var import_lodash = __toESM(require("lodash"));
const DEFAULT_TOOL_GROUP = {
  groupName: "others",
  title: '{{t("Others")}}',
  description: '{{t("Other tools")}}',
  sort: 1e3
};
class ToolManager {
  tools = new import_utils.Registry();
  groups = new import_utils.Registry();
  delegates = new Array();
  constructor() {
    this.groups.register(DEFAULT_TOOL_GROUP.groupName, DEFAULT_TOOL_GROUP);
  }
  registerToolGroup(options) {
    this.checkGroupName(options.groupName);
    this.groups.register(options.groupName, options);
  }
  registerDynamicTool(delegate) {
    this.checkGroupName(delegate.groupName);
    this.delegates.push(delegate);
  }
  registerTools(options) {
    const list = import_lodash.default.isArray(options) ? options : [options];
    list.map((x) => ({ ...x, tool: { ...x.tool } })).forEach((x) => {
      if (!x.groupName) {
        x.groupName = DEFAULT_TOOL_GROUP.groupName;
      } else {
        this.checkGroupName(x.groupName);
      }
      const toolName = `${x.groupName}-${x.tool.name}`;
      x.tool.name = toolName;
      x.tool.execution = x.tool.execution ?? "backend";
      this.tools.register(x.tool.name, x);
    });
  }
  async getTool(name, raw = false) {
    const result = await this._getTool(this.tools, name, raw);
    if (result) {
      return result;
    } else {
      const delegateTools = new import_utils.Registry();
      const [groupName] = name.split("-");
      for (const delegate of this.delegates.filter((x) => x.groupName === groupName)) {
        const tools = await delegate.getTools();
        for (const tool of tools) {
          const item = {
            ...tool
          };
          item.tool.name = `${groupName}-${item.tool.name}`;
          item.tool.execution = item.tool.execution ?? "backend";
          delegateTools.register(item.tool.name, item);
        }
      }
      return await this._getTool(delegateTools, name, raw);
    }
  }
  async listTools(raw = true) {
    const groupRegisters = Array.from(this.groups.getValues());
    const toolRegisters = Array.from(this.tools.getValues());
    for (const delegate of this.delegates) {
      let delegateTools = await delegate.getTools();
      delegateTools = delegateTools.map((item) => ({
        ...item,
        groupName: delegate.groupName,
        tool: {
          ...item.tool,
          name: `${delegate.groupName}-${item.tool.name}`,
          execution: item.tool.execution ?? "backend"
        }
      }));
      toolRegisters.push(...delegateTools);
    }
    const toolList = toolRegisters.map((x) => {
      const t = { ...x, tool: { ...x.tool } };
      t.tool.schema = this.processSchema(t.tool.schema, raw);
      return t;
    });
    const groupedTools = import_lodash.default.groupBy(toolList, (item) => item.groupName);
    return Array.from(groupRegisters).map((group) => {
      var _a;
      return {
        group,
        tools: ((_a = groupedTools[group.groupName]) == null ? void 0 : _a.map((x) => x.tool)) ?? []
      };
    }).sort((a, b) => (a.group.sort || 0) - (b.group.sort || 0));
  }
  async _getTool(register, name, raw = false) {
    const registeredTool = register.get(name);
    if (!registeredTool || !registeredTool.tool) {
      return null;
    }
    const { tool } = registeredTool;
    return {
      ...tool,
      schema: this.processSchema(tool.schema, raw)
    };
  }
  processSchema(schema, raw = false) {
    if (!schema) return void 0;
    try {
      return schema instanceof import_zod.ZodObject && raw ? schema.toJSONSchema() : schema;
    } catch (error) {
      return schema;
    }
  }
  checkGroupName(name) {
    if (!name || import_lodash.default.isEmpty(name) || name.includes("-")) {
      throw new Error("Invalid group name");
    }
  }
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  ToolManager
});
