/**
 * memory_store tool — saves learnings and failures to the PULSE brain.
 *
 * Agents can explicitly store knowledge they want to persist.
 * Quality gates apply: min 40 chars / 7 words, must contain actionable signal.
 */

import type { PulseClient } from "../client.js";

interface PluginConfig {
  agentName?: string;
}

export function createMemoryStoreTool(
  client: PulseClient,
  config: PluginConfig
) {
  return {
    name: "memory_store",
    description:
      "Save a lesson or failure to persistent PULSE memory. " +
      "Lessons are things that worked. Failures are mistakes to avoid. " +
      "Stored knowledge persists across sessions and is shared with all agents.",
    parameters: {
      type: "object" as const,
      properties: {
        content: {
          type: "string",
          description: "What to remember (min 40 chars, be specific)",
          maxLength: 2000,
        },
        type: {
          type: "string",
          enum: ["lesson", "failure"],
          description: "Whether this is a lesson (success) or failure (mistake)",
          default: "lesson",
        },
        domain: {
          type: "string",
          description:
            "Knowledge domain (e.g., security, performance, testing)",
          default: "general",
        },
      },
      required: ["content"],
    },
    execute: async (input: {
      content: string;
      type?: string;
      domain?: string;
    }) => {
      if (input.content.length > 2_000) {
        return { result: "Content too long (max 2000 characters)." };
      }
      const isFailure = input.type === "failure";
      const agentName = config.agentName || "openclaw";

      const result = await client.save(
        agentName,
        isFailure ? [] : [input.content],
        isFailure ? [input.content] : [],
        input.domain || "general",
        isFailure ? "failure" : "success"
      );

      const saved = isFailure
        ? result.failures_saved || 0
        : result.learnings_saved || 0;

      return {
        result:
          saved > 0
            ? `Saved ${input.type || "lesson"} to PULSE brain (domain: ${input.domain || "general"}).`
            : "Not saved — content may be too short, duplicate, or missing actionable signal.",
      };
    },
  };
}
