import { MemoryProvider, MemoryEntry, MemorySearchOpts } from './provider.js';

export function formatMemoryContext(entries: MemoryEntry[]): string {
  if (entries.length === 0) return '';
  const lines = entries.map(e => `[${e.type}] ${e.name}\n${e.content}`);
  return `以下是与当前对话可能相关的长期记忆：\n\n${lines.join('\n\n')}`;
}

export async function prefetchMemory(
  provider: MemoryProvider,
  userMessage: string,
  agentName: string,
  userId: string,
  limit = 5,
): Promise<string> {
  const opts: MemorySearchOpts = { agentName, userId, limit };
  let entries: MemoryEntry[];
  try {
    entries = await provider.search(userMessage, opts);
  } catch {
    entries = [];
  }
  if (entries.length === 0) {
    entries = await provider.list(opts);
  }
  return formatMemoryContext(entries);
}
