import { readFile } from "node:fs/promises";
import { fileURLToPath } from "node:url";
import { initCommand } from "./commands/init.js";
import { validateCommand } from "./commands/validate.js";
import { listCommand } from "./commands/list.js";

async function getVersion() {
  const pkgPath = fileURLToPath(new URL("../package.json", import.meta.url));
  const pkg = JSON.parse(await readFile(pkgPath, "utf8"));
  return pkg.version;
}

function helpText() {
  return [
    "antigravity-superpowers",
    "",
    "Usage:",
    "  antigravity-superpowers <command> [options]",
    "",
    "Commands:",
    "  init [dir] [--force] [--backup] [--dry-run]   Initialize .agent profile in a project",
    "  validate [dir]                                 Validate .agent profile in a project",
    "  list                                           List available skills",
    "",
    "Options:",
    "  -f, --force     Overwrite existing .agent directory",
    "  -b, --backup    Backup existing .agent before overwrite (use with --force)",
    "  -n, --dry-run   Preview files that would be copied",
    "  -v, --version   Show version",
    "  -h, --help      Show help",
  ].join("\n");
}

export async function runCli(args, io = process) {
  const [command, ...rest] = args;

  if (!command || command === "-h" || command === "--help" || command === "help") {
    io.stdout.write(`${helpText()}\n`);
    return 0;
  }

  if (command === "-v" || command === "--version") {
    const version = await getVersion();
    io.stdout.write(`${version}\n`);
    return 0;
  }

  if (command === "init") {
    return initCommand(rest, {
      cwd: io.cwd?.() ?? process.cwd(),
      stdout: io.stdout,
      stderr: io.stderr,
    });
  }

  if (command === "validate") {
    return validateCommand(rest, {
      cwd: io.cwd?.() ?? process.cwd(),
      stdout: io.stdout,
      stderr: io.stderr,
    });
  }

  if (command === "list") {
    return listCommand({
      stdout: io.stdout,
      stderr: io.stderr,
    });
  }

  io.stderr.write(`Unknown command: ${command}\n\n${helpText()}\n`);
  return 1;
}
