import { listAgents } from './runtime.js';

export function agentMemoryContext(userText) {
  const text = String(userText || '').toLowerCase();
  if (!text) return '';
  const matches = listAgents()
    .filter(agent => {
      const name = String(agent.name || '').toLowerCase();
      const id = String(agent.id || '').toLowerCase();
      return (name && text.includes(name)) || (id && text.includes(id));
    })
    .slice(0, 3);

  const blocks = matches
    .map(agent => {
      const memory = Array.isArray(agent.memory) ? agent.memory.slice(-10) : [];
      if (!memory.length) return '';
      return `<agent_memory name="${agent.name}" id="${agent.id}">
${memory.map((entry, index) => `${index + 1}. ${entry}`).join('\n')}
</agent_memory>`;
    })
    .filter(Boolean);

  if (!blocks.length) return '';
  return `\n\nReferenced agent memory for this turn:\n${blocks.join('\n\n')}`;
}
