/**
 * 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 workflow_caller_exports = {};
__export(workflow_caller_exports, {
  getWorkflowCallers: () => getWorkflowCallers
});
module.exports = __toCommonJS(workflow_caller_exports);
var import_zod = require("zod");
var import_utils = require("./utils");
var import_lodash = __toESM(require("lodash"));
const buildSchema = (config) => {
  var _a;
  const schemaProperties = {};
  if ((_a = config.parameters) == null ? void 0 : _a.length) {
    config.parameters.forEach((item) => {
      let fieldSchema;
      switch (item.type) {
        case "string":
          fieldSchema = import_zod.z.string();
          break;
        case "number":
          fieldSchema = import_zod.z.number();
          break;
        case "boolean":
          fieldSchema = import_zod.z.boolean();
          break;
        case "enum":
          if (item.options && item.options.length > 0) {
            const enumValues = item.options.map((option) => option.value);
            if (typeof enumValues[0] === "number") {
              const values = enumValues.map(String);
              fieldSchema = import_zod.z.enum(values).transform((v) => Number(v));
            } else {
              fieldSchema = import_zod.z.enum(enumValues);
            }
          } else {
            fieldSchema = import_zod.z.string();
          }
          break;
        default:
          fieldSchema = import_zod.z.any();
      }
      if (item.description) {
        fieldSchema = fieldSchema.describe(item.description);
      }
      if (!item.required) {
        fieldSchema = fieldSchema.optional();
      }
      schemaProperties[item.name] = fieldSchema;
    });
  }
  const schema = import_zod.z.object(schemaProperties);
  return schema.describe(config.description || "");
};
const invoke = async (ctx, workflow, args) => {
  var _a;
  const workflowPlugin = ctx.app.pm.get("workflow");
  const processor = await workflowPlugin.trigger(workflow, {
    ...args
  });
  const output = processor.execution.output ?? ((_a = processor.lastSavedJob) == null ? void 0 : _a.result);
  if (output == null || output === "") {
    return { status: "error", content: "No content" };
  }
  if (processor.execution.status < 0) {
    return { status: "error", content: "Workflow execution exceptions" };
  }
  const result = (0, import_utils.truncateLongStrings)(output);
  return {
    status: "success",
    content: JSON.stringify(result)
  };
};
const getWorkflowCallers = (plugin, prefix) => async (register) => {
  const workflowPlugin = plugin.app.pm.get("workflow");
  const aiSupporterWorkflows = Array.from(workflowPlugin.enabledCache.values()).filter(
    (item) => item.type === "ai-employee"
  );
  for (const workflow of aiSupporterWorkflows) {
    const config = workflow.config;
    register.registerTools({
      scope: "CUSTOM",
      introduction: {
        title: workflow.title,
        about: workflow.description
      },
      definition: {
        name: !import_lodash.default.isEmpty(prefix) ? `${prefix}-${workflow.key}` : workflow.key,
        description: workflow.description,
        schema: buildSchema(config)
      },
      invoke: async (ctx, args) => invoke(ctx, workflow, args)
    });
  }
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  getWorkflowCallers
});
