"use strict";

/**
 * openclaw config init | write | validate
 *
 * Manages /etc/openclaw/config.json — the primary OpenClaw configuration.
 */

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

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

const DEFAULT_CONFIG = {
  version: "1.0.0",
  server: {
    host: "0.0.0.0",
    port: 3100,
    workers: 2,
  },
  gateway: {
    host: "0.0.0.0",
    port: 3200,
    rateLimit: {
      windowMs: 60000,
      maxRequests: 100,
    },
  },
  workspace: {
    root: "/var/lib/openclaw",
    maxSizeMB: 1024,
  },
  mcp: {
    enabled: true,
    endpoint: "https://mcp.easyclaw.help",
  },
  logging: {
    level: "info",
    directory: "/var/log/openclaw",
  },
  security: {
    tokenExpiry: "30d",
    allowedOrigins: ["*"],
  },
};

function init(args) {
  const nonInteractive = args.includes("--non-interactive");

  console.log("Initializing OpenClaw configuration...");

  // Create config directory
  fs.mkdirSync(CONFIG_DIR, { recursive: true });
  console.log(`  Created ${CONFIG_DIR}`);

  // Write default config
  const config = { ...DEFAULT_CONFIG, instanceId: crypto.randomUUID() };
  fs.writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2) + "\n");
  console.log(`  Written ${CONFIG_FILE}`);

  if (nonInteractive) {
    console.log("  Non-interactive mode — using defaults.");
  }

  console.log("Configuration initialized successfully.");
}

function write(args) {
  console.log("Writing OpenClaw configuration...");

  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);
  }

  // Read, validate, and re-write (normalizes formatting)
  const config = JSON.parse(fs.readFileSync(CONFIG_FILE, "utf8"));
  config.updatedAt = new Date().toISOString();
  fs.writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2) + "\n");

  console.log(`  Configuration written to ${CONFIG_FILE}`);
  console.log("Configuration write complete.");
}

function validate(args) {
  console.log("Validating OpenClaw configuration...");

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

  let config;
  try {
    config = JSON.parse(fs.readFileSync(CONFIG_FILE, "utf8"));
  } catch (e) {
    console.error(`FAIL: Invalid JSON in ${CONFIG_FILE}: ${e.message}`);
    process.exit(1);
  }

  // Validate required fields
  const required = ["version", "server", "gateway", "workspace"];
  const missing = required.filter((k) => !(k in config));
  if (missing.length > 0) {
    console.error(`FAIL: Missing required fields: ${missing.join(", ")}`);
    process.exit(1);
  }

  if (!config.server.port || config.server.port < 1 || config.server.port > 65535) {
    console.error("FAIL: server.port must be between 1 and 65535");
    process.exit(1);
  }

  console.log("  version: OK");
  console.log("  server: OK");
  console.log("  gateway: OK");
  console.log("  workspace: OK");
  console.log("  logging: OK");
  console.log("Configuration is valid.");
}

function run(args) {
  const sub = args[0];
  const subArgs = args.slice(1);

  switch (sub) {
    case "init":
      return init(subArgs);
    case "write":
      return write(subArgs);
    case "validate":
      return validate(subArgs);
    default:
      console.error(`Unknown config subcommand: ${sub}`);
      console.error("Usage: openclaw config <init|write|validate>");
      process.exit(1);
  }
}

module.exports = { run };
