"use strict";

/**
 * OpenClaw Server — the main application server.
 *
 * This is the process that systemd runs via openclaw.service.
 * Listens on the configured server port (default 3100).
 */

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

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

let port = 3100;
if (fs.existsSync(CONFIG_FILE)) {
  try {
    const config = JSON.parse(fs.readFileSync(CONFIG_FILE, "utf8"));
    port = config.server?.port || 3100;
  } catch {
    // Use default
  }
}

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

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

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

// Graceful shutdown
process.on("SIGTERM", () => {
  console.log("Received SIGTERM, shutting down...");
  server.close(() => process.exit(0));
});

process.on("SIGINT", () => {
  console.log("Received SIGINT, shutting down...");
  server.close(() => process.exit(0));
});
