/**
 * memory_get tool — read specific brain regions from PULSE.
 *
 * Provides targeted access to lessons, failures, patterns, or anti-patterns.
 */

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

type BrainRegion = "lessons" | "failures" | "patterns" | "anti_patterns";

export function createMemoryGetTool(client: PulseClient) {
  return {
    name: "memory_get",
    description:
      "Read a specific section of PULSE brain memory. " +
      "Choose from: lessons (what worked), failures (what broke), " +
      "patterns (recurring observations), anti_patterns (things to avoid).",
    parameters: {
      type: "object" as const,
      properties: {
        region: {
          type: "string",
          enum: ["lessons", "failures", "patterns", "anti_patterns"],
          description: "Which brain region to read",
        },
        limit: {
          type: "number",
          description: "Max items to return (default 20)",
          default: 20,
        },
      },
      required: ["region"],
    },
    execute: async (input: { region: BrainRegion; limit?: number }) => {
      const limit = input.limit || 20;

      let items: string[] = [];
      let count = 0;

      switch (input.region) {
        case "lessons": {
          const data = await client.getLessons(limit);
          items = data.lessons;
          count = data.count;
          break;
        }
        case "failures": {
          const data = await client.getFailures(limit);
          items = data.failures;
          count = data.count;
          break;
        }
        case "patterns": {
          const data = await client.getPatterns(limit);
          items = data.patterns;
          count = data.count;
          break;
        }
        case "anti_patterns": {
          const data = await client.getAntiPatterns();
          items = (data.anti_patterns || []).map((ap: any) =>
            typeof ap === "string" ? ap : ap.description || JSON.stringify(ap)
          );
          count = data.count;
          break;
        }
      }

      if (items.length === 0) {
        return { result: `No ${input.region} found in PULSE brain.` };
      }

      const formatted = items
        .slice(0, limit)
        .map((item, i) => `${i + 1}. ${item}`)
        .join("\n");

      return {
        result: `${input.region} (${count} total, showing ${Math.min(items.length, limit)}):\n\n${formatted}`,
      };
    },
  };
}
