"use strict";

/**
 * openclaw channels init | list
 *
 * Manages OpenClaw communication channels.
 */

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

const CONFIG_DIR = "/etc/openclaw";
const CHANNELS_FILE = path.join(CONFIG_DIR, "channels.json");

const DEFAULT_CHANNELS = [
  {
    id: "default",
    name: "Default Channel",
    type: "internal",
    enabled: true,
    createdAt: new Date().toISOString(),
  },
  {
    id: "system",
    name: "System Notifications",
    type: "internal",
    enabled: true,
    createdAt: new Date().toISOString(),
  },
];

function init(args) {
  console.log("Initializing OpenClaw communication channels...");

  fs.mkdirSync(CONFIG_DIR, { recursive: true });

  fs.writeFileSync(
    CHANNELS_FILE,
    JSON.stringify({ channels: DEFAULT_CHANNELS }, null, 2) + "\n"
  );

  console.log(`  Written ${CHANNELS_FILE}`);
  console.log(`  Initialized ${DEFAULT_CHANNELS.length} default channels.`);
  console.log("Channel initialization complete.");
}

function list(args) {
  console.log("OpenClaw Communication Channels:");

  if (!fs.existsSync(CHANNELS_FILE)) {
    console.log("  No channels configured.");
    console.log('  Run "openclaw channels init" first.');
    return;
  }

  const data = JSON.parse(fs.readFileSync(CHANNELS_FILE, "utf8"));
  const channels = data.channels || [];

  if (channels.length === 0) {
    console.log("  No channels found.");
    return;
  }

  for (const ch of channels) {
    const status = ch.enabled ? "enabled" : "disabled";
    console.log(`  [${ch.id}] ${ch.name} (${ch.type}) — ${status}`);
  }

  console.log(`\n  Total: ${channels.length} channel(s)`);
}

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

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

module.exports = { run };
