const DAEMON_URL = process.env.SIGNET_DAEMON_URL || "http://localhost:3850";

async function fetchDaemon(path, body) {
  const res = await fetch(`${DAEMON_URL}${path}`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(body),
    signal: AbortSignal.timeout(5000),
  });
  if (!res.ok) throw new Error(`daemon ${res.status}`);
  return res.json();
}

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 {
        await fetchDaemon("/api/hooks/remember", {
          harness: "openclaw", who: "openclaw", content: args.trim(),
        });
        event.messages.push(`saved: ${args.trim().slice(0, 50)}...`);
      } catch (e) { event.messages.push(`Error: ${e.message}`); }
      break;
    case "recall":
      if (!args.trim()) { event.messages.push("Usage: /recall <query>"); return; }
      try {
        const data = await fetchDaemon("/api/hooks/recall", {
          harness: "openclaw", query: args.trim(),
        });
        if (data.results?.length) {
          event.messages.push(data.results.map(r => `- ${r.content}`).join("\n"));
        } else {
          event.messages.push("No memories found.");
        }
      } catch (e) { event.messages.push(`Error: ${e.message}`); }
      break;
    case "context":
      try {
        const data = await fetchDaemon("/api/hooks/session-start", {
          harness: "openclaw",
        });
        event.messages.push(data.inject || "no context");
      } catch (e) { event.messages.push(`Error: ${e.message}`); }
      break;
  }
};

export default handler;
