"use strict";

/**
 * openclaw mcp connect | status
 *
 * Manages the connection to the OpenClaw MCP knowledge base server.
 */

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

const CONFIG_FILE = "/etc/openclaw/config.json";
const MCP_STATE_FILE = "/etc/openclaw/mcp-state.json";

function getMcpEndpoint() {
  if (fs.existsSync(CONFIG_FILE)) {
    const config = JSON.parse(fs.readFileSync(CONFIG_FILE, "utf8"));
    return config.mcp?.endpoint || "https://mcp.easyclaw.help";
  }
  return "https://mcp.easyclaw.help";
}

function connect(args) {
  console.log("Connecting to OpenClaw MCP knowledge base...");

  const endpoint = getMcpEndpoint();
  console.log(`  Endpoint: ${endpoint}`);

  // Save connection state
  const state = {
    endpoint: endpoint,
    connectedAt: new Date().toISOString(),
    status: "connected",
  };

  fs.mkdirSync(path.dirname(MCP_STATE_FILE), { recursive: true });
  fs.writeFileSync(MCP_STATE_FILE, JSON.stringify(state, null, 2) + "\n");

  console.log("  Status: Connected");
  console.log("MCP knowledge base connection established.");
}

function status(args) {
  console.log("OpenClaw MCP Knowledge Base Status:");

  if (!fs.existsSync(MCP_STATE_FILE)) {
    console.log("  Status: Not connected");
    console.log('  Run "openclaw mcp connect" to establish connection.');
    return;
  }

  const state = JSON.parse(fs.readFileSync(MCP_STATE_FILE, "utf8"));
  console.log(`  Endpoint: ${state.endpoint}`);
  console.log(`  Status: ${state.status}`);
  console.log(`  Connected at: ${state.connectedAt}`);
  console.log("MCP status check complete.");
}

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

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

module.exports = { run };
