import { spawn } from "node:child_process";
import os from "node:os";

const MEMORY_SCRIPT = "/home/nicholai/.agents/memory/scripts/memory.py";

async function runMemoryScript(args) {
  return new Promise((resolve, reject) => {
    const proc = spawn("python3", [MEMORY_SCRIPT, ...args], { timeout: 5000 });
    let stdout = "", stderr = "";
    proc.stdout.on("data", (d) => { stdout += d.toString(); });
    proc.stderr.on("data", (d) => { stderr += d.toString(); });
    proc.on("close", (code) => {
      if (code === 0) resolve(stdout.trim());
      else reject(new Error(stderr || `exit code ${code}`));
    });
    proc.on("error", reject);
  });
}

const handler = async (event) => {
  if (event.type !== "command") return;
  const args = event.context?.args || "";

  switch (event.action) {
    case "remember":
      if (!args.trim()) { event.messages.push("🧠 Usage: /remember <content>"); return; }
      try {
        const result = await runMemoryScript(["save", "--mode", "explicit", "--who", "openclaw", "--content", args.trim()]);
        event.messages.push(`🧠 ${result}`);
      } catch (e) { event.messages.push(`🧠 Error: ${e.message}`); }
      break;
    case "recall":
      if (!args.trim()) { event.messages.push("🧠 Usage: /recall <query>"); return; }
      try {
        const result = await runMemoryScript(["query", args.trim(), "--limit", "10"]);
        event.messages.push(result ? `🧠 Results:\n\n${result}` : "🧠 No memories found.");
      } catch (e) { event.messages.push(`🧠 Error: ${e.message}`); }
      break;
    case "context":
      try {
        const result = await runMemoryScript(["load", "--mode", "session-start"]);
        event.messages.push(result ? `🧠 **Context**\n\n${result}` : "🧠 No context.");
      } catch (e) { event.messages.push(`🧠 Error: ${e.message}`); }
      break;
  }
};

export default handler;
