/**
 * memory_search tool — searches PULSE's 12-source brain.
 *
 * Sources: lessons, failures, patterns, predictions, anti-patterns,
 * evidence, domains, schemas, procedures, graph, private, index.
 */

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

export function createMemorySearchTool(client: PulseClient) {
  return {
    name: "memory_search",
    description:
      "Search PULSE brain for relevant memories: lessons learned, past failures, " +
      "proven patterns, predictions, anti-patterns, and domain knowledge. " +
      "Use this to recall what worked or failed in previous sessions.",
    parameters: {
      type: "object" as const,
      properties: {
        query: {
          type: "string",
          description: "What to search for in the brain",
          maxLength: 1000,
        },
      },
      required: ["query"],
    },
    execute: async (input: { query: string }) => {
      if (!input.query || input.query.length > 1_000) {
        return { result: "Query must be 1-1000 characters." };
      }
      const data = await client.search(input.query);

      // Flatten results into a readable list
      const lines: string[] = [];
      const results = data.results || {};

      for (const [source, items] of Object.entries(results)) {
        if (!Array.isArray(items) || items.length === 0) continue;
        for (const item of items) {
          const text = typeof item === "string" ? item : item.text || "";
          if (text) lines.push(`[${source}] ${text}`);
        }
      }

      if (lines.length === 0) {
        return { result: "No memories found for this query." };
      }

      return {
        result: `Found ${lines.length} memories:\n\n${lines.join("\n\n")}`,
      };
    },
  };
}
