"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 global_command_exports = {};
__export(global_command_exports, {
  GlobalCommand: () => GlobalCommand
});
module.exports = __toCommonJS(global_command_exports);
var import_sdk = require("@botpress/sdk");
var import_chalk = __toESM(require("chalk"));
var fs = __toESM(require("fs"));
var import_latest_version = __toESM(require("latest-version"));
var import_lodash = __toESM(require("lodash"));
var import_semver = __toESM(require("semver"));
var consts = __toESM(require("../consts"));
var errors = __toESM(require("../errors"));
var utils = __toESM(require("../utils"));
var import_base_command = require("./base-command");
const profileCredentialSchema = import_sdk.z.object({ apiUrl: import_sdk.z.string(), workspaceId: import_sdk.z.string(), token: import_sdk.z.string() });
class GlobalPaths extends utils.path.PathStore {
  constructor(argv) {
    const absBotpressHome = utils.path.absoluteFrom(utils.path.cwd(), argv.botpressHome);
    super({
      cliRootDir: consts.cliRootDir,
      botpressHomeDir: absBotpressHome,
      profilesPath: utils.path.absoluteFrom(absBotpressHome, consts.profileFileName),
      ...import_lodash.default.mapValues(consts.fromHomeDir, (p) => utils.path.absoluteFrom(absBotpressHome, p)),
      ...import_lodash.default.mapValues(consts.fromCliRootDir, (p) => utils.path.absoluteFrom(consts.cliRootDir, p))
    });
  }
}
class GlobalCommand extends import_base_command.BaseCommand {
  api;
  prompt;
  _pkgJson;
  constructor(api, prompt, ...args) {
    super(...args);
    this.api = api;
    this.prompt = prompt;
  }
  get globalPaths() {
    return new GlobalPaths(this.argv);
  }
  get globalCache() {
    return new utils.cache.FSKeyValueCache(this.globalPaths.abs.globalCacheFile);
  }
  async bootstrap() {
    const pkgJson = await this.readPkgJson();
    const versionText = import_chalk.default.bold(`v${pkgJson.version}`);
    this.logger.log(`Botpress CLI ${versionText}`, { prefix: "\u{1F916}" });
    await this._notifyUpdateCli();
    const paths = this.globalPaths;
    if (paths.abs.botpressHomeDir !== consts.defaultBotpressHome) {
      this.logger.log(`Using custom botpress home: ${paths.abs.botpressHomeDir}`, { prefix: "\u{1F3E0}" });
    }
  }
  teardown = async () => {
    this.logger.cleanup();
  };
  async getAuthenticatedClient(credentials) {
    try {
      const cache = this.globalCache;
      let token;
      let workspaceId;
      let apiUrl;
      if (this.argv.profile) {
        if (credentials.token || credentials.workspaceId || credentials.apiUrl) {
          this.logger.warn(
            "You are currently using credential command line arguments or environment variables as well as a profile. Your profile has overwritten the variables"
          );
        }
        ;
        ({ token, workspaceId, apiUrl } = await this.readProfileFromFS(this.argv.profile));
        this.logger.log(`Using profile "${this.argv.profile}"`, { prefix: "\u{1F464}" });
      } else {
        token = credentials.token ?? await cache.get("token");
        workspaceId = credentials.workspaceId ?? await cache.get("workspaceId");
        apiUrl = credentials.apiUrl ?? await cache.get("apiUrl");
      }
      if (!(token && workspaceId && apiUrl)) {
        return null;
      }
      if (apiUrl !== consts.defaultBotpressApiUrl) {
        this.logger.log(`Using custom url ${apiUrl}`, { prefix: "\u{1F517}" });
      }
      return this.api.newClient({ apiUrl, token, workspaceId }, this.logger);
    } catch (thrown) {
      throw errors.BotpressCLIError.wrap(thrown, "failed to create authenticated client");
    }
  }
  async readProfileFromFS(profile) {
    const parsedProfiles = await this.readProfilesFromFS();
    const profileData = parsedProfiles[profile];
    if (!profileData) {
      throw new errors.BotpressCLIError(
        `Profile "${profile}" not found in "${this.globalPaths.abs.profilesPath}". Found profiles '${Object.keys(parsedProfiles).join("', '")}'.`
      );
    }
    return profileData;
  }
  async readProfilesFromFS() {
    if (!fs.existsSync(this.globalPaths.abs.profilesPath)) {
      throw new errors.BotpressCLIError(`Profile file not found at "${this.globalPaths.abs.profilesPath}"`);
    }
    const fileContent = await fs.promises.readFile(this.globalPaths.abs.profilesPath, "utf-8");
    const parsedProfiles = JSON.parse(fileContent);
    const zodParseResult = import_sdk.z.record(profileCredentialSchema).safeParse(parsedProfiles);
    if (!zodParseResult.success) {
      throw errors.BotpressCLIError.wrap(zodParseResult.error, "Error parsing profiles: ");
    }
    return zodParseResult.data;
  }
  async writeProfileToFS(profileName, profile) {
    let profiles;
    if (fs.existsSync(this.globalPaths.abs.profilesPath)) {
      profiles = await this.readProfilesFromFS();
    } else {
      profiles = {};
    }
    profiles[profileName] = profile;
    await fs.promises.writeFile(
      this.globalPaths.abs.profilesPath,
      JSON.stringify({ [consts.defaultProfileName]: profiles.defaultProfileName, ...profiles }, null, 2),
      "utf-8"
    );
  }
  async ensureLoginAndCreateClient(credentials) {
    const client = await this.getAuthenticatedClient(credentials);
    if (client === null) {
      throw new errors.NotLoggedInError();
    }
    return client;
  }
  _notifyUpdateCli = async () => {
    try {
      this.logger.debug("Checking if cli is up to date");
      const pkgJson = await this.readPkgJson();
      if (!pkgJson.version) {
        throw new errors.BotpressCLIError("Could not find version in package.json");
      }
      const latest = await (0, import_latest_version.default)(pkgJson.name);
      const isOutdated = import_semver.default.lt(pkgJson.version, latest);
      if (isOutdated) {
        this.logger.box(
          [
            `${import_chalk.default.bold("Update available")} ${import_chalk.default.dim(pkgJson.version)} \u2192 ${import_chalk.default.green(latest)}`,
            "",
            "To update, run:",
            `  for npm  ${import_chalk.default.cyan(`npm i -g ${pkgJson.name}`)}`,
            `  for yarn ${import_chalk.default.cyan(`yarn global add ${pkgJson.name}`)}`,
            `  for pnpm ${import_chalk.default.cyan(`pnpm i -g ${pkgJson.name}`)}`
          ].join("\n")
        );
      }
    } catch (thrown) {
      const err = errors.BotpressCLIError.map(thrown);
      this.logger.debug(`Failed to check if cli is up to date: ${err.message}`);
    }
  };
  async readPkgJson() {
    if (this._pkgJson) {
      return this._pkgJson;
    }
    const { cliRootDir } = this.globalPaths.abs;
    const pkgJson = await utils.pkgJson.readPackageJson(cliRootDir);
    if (!pkgJson) {
      throw new errors.BotpressCLIError(`Could not find package.json at "${cliRootDir}"`);
    }
    this._pkgJson = pkgJson;
    return pkgJson;
  }
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  GlobalCommand
});
//# sourceMappingURL=global-command.js.map
