/**
 * @module cli
 * @description Main CLI functionality for configuring and running commands
 */

import { Command } from "commander";
import { createShopifyCommand } from "./commands/shopify/index.js";
import { createLogger } from "./utils/logger.js";

const logger = createLogger("cli");

/**
 * Creates and configures the root CLI command
 *
 * Sets up the main program with all available commands and global options.
 * Currently supports Shopify commands, with a structure that allows easy
 * addition of commands for other e-commerce platforms.
 *
 * @returns The configured Command object ready to be run
 *
 * @example
 * ```typescript
 * const program = createCli();
 * program.parse(process.argv);
 * ```
 */
export function createCli(): Command {
  const program = new Command()
    .name("dsco-theme")
    .description("CLI tool for working with e-commerce themes")
    .version(process.env.npm_package_version || "1.0.0");

  // Add Shopify command
  program.addCommand(createShopifyCommand());

  // Here, you can add other platform commands in the future
  // For example:
  // program.addCommand(createBigCommerceCommand());
  // program.addCommand(createWooCommerceCommand());

  // Handle errors
  program.showHelpAfterError();
  program.showSuggestionAfterError();

  return program;
}

/**
 * Runs the CLI with the given arguments
 *
 * Parses the arguments and executes the appropriate command.
 * Handles any errors that might occur during command execution.
 *
 * @param args - Command line arguments (defaults to process.argv)
 * @returns A promise that resolves when the command completes
 *
 * @example
 * ```typescript
 * // Run with default arguments
 * await runCli();
 *
 * // Run with custom arguments
 * await runCli(['node', 'script.js', 'shopify', 'theme', 'init']);
 * ```
 */
export async function runCli(args: string[] = process.argv): Promise<void> {
  try {
    await createCli().parseAsync(args);
  } catch (error) {
    logger.error(`${(error as Error).message}`);
    process.exit(1);
  }
}
