#!/usr/bin/env node
const { program, Option } = require("commander");
const { getLocalPkgInfo } = require("./lib/utils");
const { statusCommand, stopCommand, killCommand, fixCommand } = require("./lib/commands");
const { main } = require("./lib/startup");

const { pkg } = getLocalPkgInfo();

function portArg(v) {
  return parseInt(v, 10);
}

// Global options
program
  .name("comphub")
  .option("-p, --port <number>", "Startup port", portArg)
  .option("-d, --dir <path>", "Resource directory relative path")
  .version(pkg.version, "-v, --version", "Show version")
  .addOption(new Option("--allow-debug", "Enable debug mode").hideHelp())
  .addOption(new Option("--api <url>", "API URL").hideHelp())
  .helpOption("-h, --help", "Show help");

// status subcommand: view master status and all projects
program
  .command("status")
  .description("View master service status and all running projects")
  .addOption(new Option("-p, --port <number>", "Master port").argParser(portArg).hideHelp())
  .action(statusCommand);

// stop subcommand: stop projects
program
  .command("stop [hash]")
  .description("Stop a specific project (by hash) or stop all projects (--all)")
  .addOption(new Option("-p, --port <number>", "Master port").argParser(portArg).hideHelp())
  .option("-a, --all", "Stop all projects")
  .action(stopCommand);

// kill subcommand: shutdown master process
program.command("kill").description("Shutdown master process").addOption(new Option("-p, --port <number>", "Master port").argParser(portArg).hideHelp()).action(killCommand);

// fix subcommand: clean up stale runtime file
program.command("fix").description("Fix common issues (stale runtime file, etc.)").action(fixCommand);

// Default startup command
program.action(async () => {
  try {
    await main(pkg, program.opts());
  } catch (e) {
    console.error(`✗ Startup failed: ${e.message}`);
    process.exit(1);
  }
});

program.parse();
