import fs from 'node:fs/promises';
import { getAgentsDir, getAgentConfigPath } from './paths.js';

export async function listAgents() {
  const agentsDir = getAgentsDir();
  let entries;
  try {
    entries = await fs.readdir(agentsDir, { withFileTypes: true });
  } catch {
    return [];
  }

  const agents = [];
  for (const entry of entries) {
    if (!entry.isDirectory()) continue;
    const cfgPath = getAgentConfigPath(entry.name);
    try {
      const raw = await fs.readFile(cfgPath, 'utf-8');
      const data = JSON.parse(raw);
      agents.push({
        agent_id: data.agent_id || entry.name,
        version: data.version || '0.0.0',
        description: data.description || '',
      });
    } catch {
      // skip directories without a valid .config.json
    }
  }

  return agents.sort((a, b) => a.agent_id.localeCompare(b.agent_id));
}

export async function findAgent(agentId) {
  const agents = await listAgents();
  return agents.find((a) => a.agent_id === agentId) || null;
}
