#!/usr/bin/env node
"use strict";

/**
 * OpenClaw CLI — main entry point.
 *
 * Routes subcommands to their respective handlers in lib/.
 * Usage: openclaw <command> [subcommand] [options]
 */

const path = require("path");

const COMMANDS = {
  config: () => require("../lib/config"),
  token: () => require("../lib/token"),
  env: () => require("../lib/env"),
  workspace: () => require("../lib/workspace"),
  gateway: () => require("../lib/gateway"),
  service: () => require("../lib/service"),
  mcp: () => require("../lib/mcp"),
  channels: () => require("../lib/channels"),
  health: () => require("../lib/health"),
};

const VERSION = require("../package.json").version;

function printUsage() {
  console.log(`OpenClaw CLI v${VERSION}`);
  console.log("");
  console.log("Usage: openclaw <command> [subcommand] [options]");
  console.log("");
  console.log("Commands:");
  console.log("  config    init | write | validate    Manage configuration");
  console.log("  token     generate                   Generate auth token");
  console.log("  env       setup                      Set up environment variables");
  console.log("  workspace init | validate             Manage workspace directories");
  console.log("  gateway   install | configure         API gateway management");
  console.log("  service   install                     Install systemd services");
  console.log("  mcp       connect | status            MCP knowledge base");
  console.log("  channels  init | list                 Communication channels");
  console.log("  health    [--full]                    Health checks");
  console.log("");
  console.log("Options:");
  console.log("  --version    Show version number");
  console.log("  --help       Show this help message");
}

// --- Main ---
const args = process.argv.slice(2);

if (args.length === 0 || args.includes("--help") || args.includes("-h")) {
  printUsage();
  process.exit(0);
}

if (args.includes("--version") || args.includes("-v")) {
  console.log(`openclaw v${VERSION}`);
  process.exit(0);
}

const command = args[0];
const subArgs = args.slice(1);

if (!COMMANDS[command]) {
  console.error(`Unknown command: ${command}`);
  console.error('Run "openclaw --help" for usage information.');
  process.exit(1);
}

try {
  const handler = COMMANDS[command]();
  handler.run(subArgs);
} catch (err) {
  console.error(`Error: ${err.message}`);
  process.exit(1);
}
