/**
 * loadRecentMemory — load recent agent outcomes from Brain at boot.
 *
 * Promoted from forge/src/agents/shared/startup.ts (Vague 1.B.2).
 * Forge-specific coupling neutralized:
 * - "forge_outcome" category → parameterizable
 * - "forge" tag → parameterizable
 *
 * @public @since 0.17.0
 */

import type { BrainPort, BrainEntry } from "../ports/brain.js";

// ─── LoadRecentMemoryOptions ─────────────────────────────────────────────────

/**
 * Options for loadRecentMemory.
 *
 * @public
 */
export interface LoadRecentMemoryOptions {
  /** Brain category for outcome entries (default: "outcome"). */
  category?: string;
  /** Additional tags to filter entries (default: [agentId]). */
  tags?: string[];
  /** Maximum number of entries to load (default: 5). */
  limit?: number;
  /** Maximum total characters for the returned summary (default: 2000). */
  maxChars?: number;
  /** Maximum characters per entry preview (default: 300). */
  maxEntryChars?: number;
}

// ─── loadRecentMemory ────────────────────────────────────────────────────────

/**
 * Load recent outcomes for an agent from Brain and return a concise text summary.
 *
 * Returns an empty string when Brain is unavailable or no entries exist —
 * never throws, so agents can boot even when Brain is temporarily down.
 *
 * @example
 * ```ts
 * const memory = await loadRecentMemory(brain, "forge-revenue", {
 *   category: "forge_outcome",
 *   tags: ["forge", "agent:forge-revenue", "outcome"],
 * });
 * // → "2026-05-07: Revenue cycle completed: 3 leads qualified...\n..."
 * ```
 *
 * @public
 */
export async function loadRecentMemory(
  brain: BrainPort,
  agentId: string,
  opts: LoadRecentMemoryOptions = {}
): Promise<string> {
  const {
    category = "outcome",
    tags,
    limit = 5,
    maxChars = 2000,
    maxEntryChars = 300,
  } = opts;

  const effectiveTags = tags ?? [agentId];

  let entries: BrainEntry[] = [];
  try {
    entries =
      (await brain.queryKnowledge?.("recent outcomes", {
        category,
        tags: effectiveTags,
        limit,
      })) ?? [];
  } catch {
    // Non-fatal: agent can still boot without memory
    return "";
  }

  return entries
    .map((e) => {
      const date = e.created_at ?? "unknown";
      const preview =
        e.content.length > maxEntryChars
          ? e.content.slice(0, maxEntryChars) + "..."
          : e.content;
      return `${date}: ${preview}`;
    })
    .join("\n")
    .slice(0, maxChars);
}
