"use strict";
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 chat_command_exports = {};
__export(chat_command_exports, {
  ChatCommand: () => ChatCommand
});
module.exports = __toCommonJS(chat_command_exports);
var chat = __toESM(require("@botpress/chat"));
var import_semver = __toESM(require("semver"));
var import_chat = require("../chat");
var consts = __toESM(require("../consts"));
var errors = __toESM(require("../errors"));
var utils = __toESM(require("../utils"));
var import_global_command = require("./global-command");
class ChatCommand extends import_global_command.GlobalCommand {
  async run() {
    if (process.platform === "win32") {
      this.logger.warn("The chat command was not tested on Windows and may not work as expected");
    }
    const api = await this.ensureLoginAndCreateClient(this.argv);
    const botId = this.argv.botId ?? await this._selectBot(api);
    const { bot } = await api.client.getBot({ id: botId }).catch((thrown) => {
      throw errors.BotpressCLIError.wrap(thrown, `Could not fetch bot "${botId}"`);
    });
    const targetChatVersion = this._getChatApiTargetVersionRange();
    let chatIntegrationInstance = this._findChatInstance(bot);
    if (!chatIntegrationInstance) {
      this.logger.log(`Chat integration with version ${targetChatVersion} is not installed in the selected bot`);
      const confirmInstall = await this.prompt.confirm("Do you wish to install it now?");
      if (!confirmInstall) {
        throw new errors.BotpressCLIError("Chat integration is required to proceed");
      }
      chatIntegrationInstance = await this._installChatIntegration(api, botId);
    }
    const { webhookId } = chatIntegrationInstance.instance;
    const chatApiBaseUrl = this._getChatApiUrl(api);
    this.logger.debug(`using chat api url: "${chatApiBaseUrl}"`);
    const chatApiUrl = `${chatApiBaseUrl}/${webhookId}`;
    const chatClient = await chat.Client.connect({ apiUrl: chatApiUrl });
    await this._chat(chatClient);
  }
  _chat = async (client2) => {
    const convLine = this.logger.line();
    convLine.started("Creating a conversation...");
    const { conversation } = await client2.createConversation({});
    convLine.success(`Conversation created with id "${conversation.id}"`);
    convLine.commit();
    const chat2 = import_chat.Chat.launch({ client: client2, conversationId: conversation.id });
    await chat2.wait();
  };
  _getChatApiUrl = (api) => {
    if (this.argv.chatApiUrl) {
      return this.argv.chatApiUrl;
    }
    const parseResult = utils.url.parse(api.url);
    if (parseResult.status === "error") {
      return consts.defaultChatApiUrl;
    }
    const { host, ...url } = parseResult.url;
    if (!host.startsWith("api.")) {
      return consts.defaultChatApiUrl;
    }
    const newHost = host.replace("api.", "chat.");
    return utils.url.format({ ...url, host: newHost });
  };
  _selectBot = async (api) => {
    const availableBots = await api.listAllPages(api.client.listBots, (r) => r.bots).catch((thrown) => {
      throw errors.BotpressCLIError.wrap(thrown, "Could not fetch existing bots");
    });
    if (!availableBots.length) {
      throw new errors.NoBotsFoundError();
    }
    const prompted = await this.prompt.select("Which bot do you want to deploy?", {
      choices: availableBots.map((bot) => ({ title: bot.name, value: bot.id }))
    });
    if (!prompted) {
      throw new errors.ParamRequiredError("Bot Id");
    }
    return prompted;
  };
  _installChatIntegration = async (api, botId) => {
    const line = this.logger.line();
    line.started("Installing chat integration...");
    const { integration } = await api.client.getPublicIntegration({
      name: "chat",
      version: this._getChatApiTargetVersion()
    });
    const { bot } = await api.client.updateBot({
      id: botId,
      integrations: {
        [integration.name]: {
          integrationId: integration.id,
          enabled: true,
          configuration: {}
          // empty object will always be a valid chat integration configuration
        }
      }
    });
    line.success("Chat integration installed");
    line.commit();
    const inst = this._findChatInstance(bot);
    if (!inst) {
      throw new errors.BotpressCLIError("Chat integration was installed but could not be found");
    }
    return inst;
  };
  _findChatInstance = (bot) => {
    const integrationInstances = Object.entries(bot.integrations).map(([alias, integrationInstance]) => ({
      alias,
      instance: integrationInstance
    }));
    const targetChatVersion = this._getChatApiTargetVersionRange();
    return integrationInstances.find(
      (i) => i.instance.name === "chat" && (import_semver.default.satisfies(i.instance.version, targetChatVersion) || i.instance.version === "dev")
    );
  };
  _getChatApiTargetVersionRange = () => {
    const targetApiVersion = this._getChatApiTargetVersion();
    const nextMajor = import_semver.default.inc(targetApiVersion, "major");
    return `>=${targetApiVersion} <${nextMajor}`;
  };
  _getChatApiTargetVersion = () => {
    const dummyClient = new chat.Client({ apiUrl: "" });
    return dummyClient.apiVersion;
  };
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  ChatCommand
});
//# sourceMappingURL=chat-command.js.map
