"use strict";

/**
 * openclaw env setup
 *
 * Creates /etc/openclaw/env with environment variables for the OpenClaw services.
 */

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

const CONFIG_DIR = "/etc/openclaw";
const ENV_FILE = path.join(CONFIG_DIR, "env");
const CONFIG_FILE = path.join(CONFIG_DIR, "config.json");
const TOKEN_FILE = path.join(CONFIG_DIR, "token");

function setup(args) {
  console.log("Setting up OpenClaw environment variables...");

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

  const config = JSON.parse(fs.readFileSync(CONFIG_FILE, "utf8"));

  // Read token if it exists
  let token = "";
  if (fs.existsSync(TOKEN_FILE)) {
    token = fs.readFileSync(TOKEN_FILE, "utf8").trim();
  }

  // Build environment file
  const envContent = [
    "# OpenClaw Environment Variables",
    `# Generated: ${new Date().toISOString()}`,
    "",
    `OPENCLAW_CONFIG=${CONFIG_FILE}`,
    `OPENCLAW_HOST=${config.server.host}`,
    `OPENCLAW_PORT=${config.server.port}`,
    `OPENCLAW_GATEWAY_PORT=${config.gateway.port}`,
    `OPENCLAW_WORKSPACE=${config.workspace.root}`,
    `OPENCLAW_LOG_DIR=${config.logging.directory}`,
    `OPENCLAW_LOG_LEVEL=${config.logging.level}`,
    token ? `OPENCLAW_TOKEN=${token}` : "# OPENCLAW_TOKEN=(not set — run openclaw token generate)",
    `NODE_ENV=production`,
    "",
  ].join("\n");

  fs.writeFileSync(ENV_FILE, envContent, { mode: 0o600 });

  console.log(`  Environment file written to ${ENV_FILE}`);
  console.log("Environment setup complete.");
}

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

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

module.exports = { run };
