#!/usr/bin/env node

/**
 * @module index
 * @description Entry point for the theme-cli package
 *
 * This file is the main entry point for the CLI and exports
 * all public APIs of the package to make them available for
 * programmatic usage.
 */

// Add immediate logging
console.log("Starting CLI execution...");

// Import and run the CLI
import { runCli } from "./cli.js";

// Re-export public APIs
export { createCli, runCli } from "./cli.js";
export { createLogger } from "./utils/logger.js";
export { downloadFile, downloadAndSaveFile } from "./utils/download.js";
export { extractZip } from "./utils/zip.js";
export { initShopifyTheme } from "./commands/shopify/theme/init.js";

// Export types
export * from "./types/index.js";

// Set exit code on unhandled rejections
process.on("unhandledRejection", (reason) => {
  console.error("Unhandled Rejection:", reason);
  process.exit(1);
});

// Check if we're being run as a script
console.log("Checking execution context...");
console.log("Process argv:", process.argv);

// Run the CLI if:
// 1. We're being run directly as a script (process.argv[1] ends with our script name)
// 2. We're being run through npx (process.argv[1] includes our package name)
// 3. We're being run as a module but with CLI arguments
const isRunningAsCLI =
  process.argv[1]?.endsWith("theme-cli") ||
  process.argv[1]?.includes("@dscodotco/theme-cli") ||
  (process.argv.length > 2 && process.argv[2] === "shopify");

if (isRunningAsCLI) {
  console.log("Running as CLI...");
  // Properly handle the async nature of runCli
  runCli().catch((error) => {
    console.error("CLI execution error:", error);
    process.exit(1);
  });
} else {
  console.log("Running as module - exports available for programmatic use");
}
