/**
 * 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_exports = {};
__export(ai_exports, {
  default: () => ai_default
});
module.exports = __toCommonJS(ai_exports);
var import_lodash = __toESM(require("lodash"));
var import_recommended_models = require("../../common/recommended-models");
const aiResource = {
  name: "ai",
  actions: {
    listLLMProviders: async (ctx, next) => {
      const plugin = ctx.app.pm.get("ai");
      ctx.body = plugin.aiManager.listLLMProviders();
      await next();
    },
    listLLMServices: async (ctx, next) => {
      const plugin = ctx.app.pm.get("ai");
      const { model } = ctx.action.params;
      const filter = ctx.action.params.filter ?? {};
      filter.enabled = { $ne: false };
      if (model) {
        const supportedProvider = plugin.aiManager.getSupportedProvider(model);
        if (!supportedProvider || import_lodash.default.isEmpty(supportedProvider)) {
          ctx.body = [];
          await next();
          return;
        }
        filter.provider = {
          $in: supportedProvider
        };
      }
      const serviceList = await ctx.db.getRepository("llmServices").find({
        filter
      });
      ctx.body = serviceList.map((x) => x.dataValues).map(({ options, ...rest }) => ({ ...rest }));
      await next();
    },
    listModels: async (ctx, next) => {
      var _a;
      const { llmService, model } = ctx.action.params;
      const plugin = ctx.app.pm.get("ai");
      const service = await ctx.db.getRepository("llmServices").findOne({
        filter: {
          name: llmService
        }
      });
      if (!service) {
        ctx.throw(400, "invalid llm service");
      }
      const providerOptions = plugin.aiManager.llmProviders.get(service.provider);
      if (!providerOptions) {
        ctx.throw(400, "invalid llm provider");
      }
      const options = service.options;
      const Provider = providerOptions.provider;
      const provider = new Provider({
        app: ctx.app,
        serviceOptions: options
      });
      if (model && providerOptions.supportedModel.includes(model)) {
        ctx.body = ((_a = providerOptions.models) == null ? void 0 : _a[model].map((id) => ({ id }))) ?? [];
      } else {
        const res = await provider.listModels();
        if (res.errMsg) {
          ctx.log.error(res.errMsg);
          ctx.throw(
            res.code || 500,
            `${ctx.t("Get models list failed, you can enter a model name manually.")} ${res.errMsg}`
          );
        }
        ctx.body = res.models || [];
      }
      return next();
    },
    listProviderModels: async (ctx, next) => {
      const { provider, options, model } = ctx.action.params.values ?? {};
      const plugin = ctx.app.pm.get("ai");
      const providerOptions = plugin.aiManager.llmProviders.get(provider);
      if (!providerOptions) {
        ctx.throw(400, "invalid llm provider");
      }
      const Provider = providerOptions.provider;
      const providerClient = new Provider({
        app: ctx.app,
        serviceOptions: options
      });
      const res = await providerClient.listModels();
      if (res.errMsg) {
        ctx.log.error(res.errMsg);
        ctx.throw(
          res.code || 500,
          `${ctx.t("Get models list failed, you can enter a model name manually.")} ${res.errMsg}`
        );
      }
      const models = res.models || [];
      if (model) {
        ctx.body = models.filter((m) => m.id.toLowerCase().includes(model.toLowerCase()));
      } else {
        ctx.body = models;
      }
      return next();
    },
    testFlight: async (ctx, next) => {
      const { provider, options, model } = ctx.action.params.values ?? {};
      const plugin = ctx.app.pm.get("ai");
      const providerOptions = plugin.aiManager.llmProviders.get(provider);
      if (!providerOptions) {
        ctx.throw(400, "invalid llm provider");
      }
      const Provider = providerOptions.provider;
      const providerClient = new Provider({
        app: ctx.app,
        serviceOptions: options,
        modelOptions: {
          model,
          responseFormat: "text"
        }
      });
      ctx.body = await providerClient.testFlight();
      return next();
    },
    listAllEnabledModels: async (ctx, next) => {
      const plugin = ctx.app.pm.get("ai");
      const services = await ctx.db.getRepository("llmServices").find({ sort: "sort" });
      const llmServices = services.filter((service) => service.enabled !== false).map((service) => {
        const raw = service.enabledModels;
        let enabledModels;
        if (raw && typeof raw === "object" && !Array.isArray(raw) && raw.mode) {
          if (raw.mode === "recommended") {
            enabledModels = (0, import_recommended_models.getRecommendedModels)(service.provider);
          } else {
            enabledModels = (raw.models || []).filter((m) => m.value).map((m) => ({
              label: m.label || m.value,
              value: m.value
            }));
          }
        } else if (Array.isArray(raw)) {
          if (raw.length === 0) {
            enabledModels = (0, import_recommended_models.getRecommendedModels)(service.provider);
          } else {
            enabledModels = raw.map((id) => ({ label: id, value: id }));
          }
        } else {
          enabledModels = (0, import_recommended_models.getRecommendedModels)(service.provider);
        }
        if (enabledModels.length === 0) {
          return null;
        }
        const providerMeta = plugin.aiManager.llmProviders.get(service.provider);
        const P = providerMeta.provider;
        const p = new P({ app: ctx.app });
        const isToolConflict = p.isToolConflict();
        return {
          llmService: service.name,
          llmServiceTitle: service.title,
          provider: service.provider,
          providerTitle: providerMeta == null ? void 0 : providerMeta.title,
          enabledModels,
          supportWebSearch: (providerMeta == null ? void 0 : providerMeta.supportWebSearch) ?? false,
          isToolConflict
        };
      }).filter(Boolean);
      ctx.body = llmServices;
      await next();
    }
  }
};
var ai_default = aiResource;
