"use strict";

/**
 * openclaw token generate
 *
 * Generates an authentication token and stores it at /etc/openclaw/token.
 */

const fs = require("fs");
const path = require("path");
const crypto = require("crypto");

const CONFIG_DIR = "/etc/openclaw";
const TOKEN_FILE = path.join(CONFIG_DIR, "token");

function generate(args) {
  console.log("Generating OpenClaw authentication token...");

  if (!fs.existsSync(CONFIG_DIR)) {
    console.error(`Error: Config directory not found at ${CONFIG_DIR}`);
    console.error('Run "openclaw config init" first.');
    process.exit(1);
  }

  // Generate a secure random token
  const token = `oc_${crypto.randomBytes(32).toString("hex")}`;

  // Write token file with restrictive permissions
  fs.writeFileSync(TOKEN_FILE, token + "\n", { mode: 0o600 });

  console.log(`  Token written to ${TOKEN_FILE}`);
  console.log(`  Token prefix: ${token.substring(0, 10)}...`);
  console.log("Token generated successfully.");
}

function run(args) {
  const sub = args[0];

  switch (sub) {
    case "generate":
      return generate(args.slice(1));
    default:
      console.error(`Unknown token subcommand: ${sub}`);
      console.error("Usage: openclaw token generate");
      process.exit(1);
  }
}

module.exports = { run };
