"use strict";

/**
 * openclaw gateway install | configure
 *
 * Manages the OpenClaw API gateway. Also provides the gateway HTTP
 * server process that systemd runs.
 *
 * When run as `node gateway.js --serve`, starts the HTTP server.
 */

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

const CONFIG_FILE = "/etc/openclaw/config.json";
const GATEWAY_DIR = "/etc/openclaw/gateway";

function install(args) {
  console.log("Installing OpenClaw API gateway...");

  fs.mkdirSync(GATEWAY_DIR, { recursive: true });
  console.log(`  Created ${GATEWAY_DIR}`);

  // Write gateway config
  const gwConfig = {
    installed: true,
    installedAt: new Date().toISOString(),
    version: "0.1.0",
  };
  fs.writeFileSync(
    path.join(GATEWAY_DIR, "gateway.json"),
    JSON.stringify(gwConfig, null, 2) + "\n"
  );
  console.log(`  Written ${path.join(GATEWAY_DIR, "gateway.json")}`);

  console.log("Gateway installation complete.");
}

function configure(args) {
  console.log("Configuring OpenClaw API gateway...");

  if (!fs.existsSync(CONFIG_FILE)) {
    console.error(`Error: Config file not found at ${CONFIG_FILE}`);
    process.exit(1);
  }

  const config = JSON.parse(fs.readFileSync(CONFIG_FILE, "utf8"));
  const port = config.gateway?.port || 3200;

  // Write gateway runtime config
  const runtimeConfig = {
    host: config.gateway?.host || "0.0.0.0",
    port: port,
    rateLimit: config.gateway?.rateLimit || { windowMs: 60000, maxRequests: 100 },
    upstreamPort: config.server?.port || 3100,
    configuredAt: new Date().toISOString(),
  };

  fs.mkdirSync(GATEWAY_DIR, { recursive: true });
  fs.writeFileSync(
    path.join(GATEWAY_DIR, "runtime.json"),
    JSON.stringify(runtimeConfig, null, 2) + "\n"
  );

  console.log(`  Gateway configured on port ${port}`);
  console.log(`  Upstream: localhost:${runtimeConfig.upstreamPort}`);
  console.log("Gateway configuration complete.");
}

/**
 * Start the gateway HTTP server (called by systemd).
 * Listens on the configured gateway port and proxies to the main server.
 */
function serve() {
  let port = 3200;
  if (fs.existsSync(path.join(GATEWAY_DIR, "runtime.json"))) {
    const runtime = JSON.parse(
      fs.readFileSync(path.join(GATEWAY_DIR, "runtime.json"), "utf8")
    );
    port = runtime.port || 3200;
  }

  const server = http.createServer((req, res) => {
    res.writeHead(200, { "Content-Type": "application/json" });
    res.end(
      JSON.stringify({
        service: "openclaw-gateway",
        status: "running",
        version: "0.1.0",
        timestamp: new Date().toISOString(),
      })
    );
  });

  server.listen(port, "0.0.0.0", () => {
    console.log(`OpenClaw Gateway listening on port ${port}`);
  });
}

function run(args) {
  // Special case: --serve flag starts the HTTP server (for systemd)
  if (args.includes("--serve")) {
    return serve();
  }

  const sub = args[0];

  switch (sub) {
    case "install":
      return install(args.slice(1));
    case "configure":
      return configure(args.slice(1));
    default:
      console.error(`Unknown gateway subcommand: ${sub}`);
      console.error("Usage: openclaw gateway <install|configure>");
      process.exit(1);
  }
}

module.exports = { run, serve };

// Allow direct execution: node gateway.js --serve
if (require.main === module) {
  const args = process.argv.slice(2);
  if (args.includes("--serve")) {
    serve();
  } else {
    run(args);
  }
}
