#! /usr/bin/env node

/** Required to set max width of the help commands */
const oldWidth = process.stdout.columns
process.stdout.columns = 100
/** ---------------------------------------------- */

const program = require("commander");
const chalk = require("chalk");
const { version } = require("./package.json");
const { commandDescriptions, cliConfig } = require("./lib/parser");
const { client } = require("./lib/commands/generic");
const inquirer = require("inquirer");
{% if sdk.test != "true" %}
const { login, logout, whoami, migrate, register } = require("./lib/commands/generic");
const { init } = require("./lib/commands/init");
const { pull } = require("./lib/commands/pull");
const { run } = require("./lib/commands/run");
const { push, deploy } = require("./lib/commands/push");
{% else %}
const { migrate } = require("./lib/commands/generic");
{% endif %}
{% for service in spec.services %}
const { {{ service.name | caseLower }} } = require("./lib/commands/{{ service.name | caseLower }}");
{% endfor %}

inquirer.registerPrompt('search-list', require('inquirer-search-list'));

program
  .description(commandDescriptions['main'])
  .configureHelp({
    helpWidth: process.stdout.columns || 80,
    sortSubcommands: true,
  })
  .helpOption('-h, --help', "Display help for command")
  .version(version, "-v, --version", "Output the version number")
  .option("-V, --verbose", "Show complete error log")
  .option("-j, --json", "Output in JSON format")
  .hook('preAction', migrate)
  .option("-f,--force", "Flag to confirm all warnings")
  .option("-a,--all", "Flag to push all resources")
  .option("--id [id...]", "Flag to pass a list of ids for a given action")
  .option("--report", "Enable reporting in case of CLI errors")
  .on("option:json", () => {
    cliConfig.json = true;
  })
  .on("option:verbose", () => {
    cliConfig.verbose = true;
  })
  .on("option:report", function() {
    cliConfig.report = true;
    cliConfig.reportData = { data: this };
  })
  .on("option:force", () => {
    cliConfig.force = true;
  })
  .on("option:all", () => {
    cliConfig.all = true;
  })
  .on("option:id", function() {
    cliConfig.ids = this.opts().id;
  })
  .showSuggestionAfterError()
{% if sdk.test != "true" %}
  .addCommand(whoami)
  .addCommand(register)
  .addCommand(login)
  .addCommand(init)
  .addCommand(pull)
  .addCommand(push)
  .addCommand(deploy)
  .addCommand(run)
  .addCommand(logout)
{% endif %}
{% for service in spec.services %}
  .addCommand({{ service.name | caseLower }})
{% endfor %}
  .addCommand(client)
  .parse(process.argv);

process.stdout.columns = oldWidth;
