import { activate } from "./index.js";

const plugin = {};
activate(plugin);

async function run() {
  const userId = "golem-openclaw-test";
  const timestamp = new Date().toISOString();
  const text = `openclaw-mem0-python plugin test at ${timestamp}`;

  const baseUrl = process.env.MEM0_BASE_URL || "http://192.168.0.200:8420";

  console.log("Writing memory...");
  const writeResult = await plugin.write({ text, userId });
  console.log("Write result:", writeResult);

  console.log("Searching memory...");
  const searchResult = await plugin.search({ query: "openclaw-mem0-python", userId });
  console.log("Search result:", searchResult);

  console.log("Reading recent memories...");
  const readResult = await plugin.read({ userId, limit: 3 });
  console.log("Read result:", readResult);

  console.log("Listing knowledge sources...");
  const sources = await plugin.listKnowledgeSources();
  console.log("Sources:", sources);

  const firstSource = sources?.sources?.[0]?.source_file;
  if (firstSource) {
    console.log("Describing knowledge book:", firstSource);
    const describe = await plugin.describeKnowledgeBook({ sourceFile: firstSource });
    console.log("Describe:", describe.summary);

    console.log("Searching knowledge book...");
    const bookSearch = await plugin.searchKnowledgeBook({
      query: describe?.hintQuery || "introduction",
      sourceFile: firstSource,
      limit: 3,
    });
    console.log("Book search:", bookSearch);
  } else {
    console.log("No knowledge sources found; skipping book tests.");
  }

  console.log("Cleaning up test memories...");
  const allRes = await fetch(`${baseUrl}/memories/all`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ user_id: userId }),
  }).then((r) => r.json());

  const ids = (allRes?.results || []).map((r) => r.id).filter(Boolean);
  for (const id of ids) {
    await fetch(`${baseUrl}/memory/${id}`, {
      method: "DELETE",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ collection: "conversational" }),
    });
  }
  console.log(`Cleanup done (${ids.length} deleted).`);
}

run().catch((err) => {
  console.error("Test failed:", err);
  process.exit(1);
});
