/**
 * List 命令实现
 * 列出所有子Agent配置
 */

const fs = require('fs');
const path = require('path');

/**
 * 列出 .agent/agents 目录下的所有 Agent 配置
 */
async function listCommand() {
  const agentsDir = path.resolve(process.cwd(), '.agent', 'agents');

  if (!fs.existsSync(agentsDir)) {
    console.log('No .agent/agents directory found.');
    console.log('Create agents by adding files to: .agent/agents/');
    return;
  }

  const entries = fs.readdirSync(agentsDir, { withFileTypes: true });
  const agents = [];

  for (const entry of entries) {
    if (
      entry.isFile() &&
      (entry.name.endsWith('.js') || entry.name.endsWith('.json') || entry.name.endsWith('.md'))
    ) {
      const baseName = entry.name.replace(/\.(js|json|md)$/, '');
      const filePath = path.join(agentsDir, entry.name);

      try {
        let config = { name: baseName };

        if (entry.name.endsWith('.json')) {
          const content = fs.readFileSync(filePath, 'utf-8');
          config = { ...config, ...JSON.parse(content) };
        } else if (entry.name.endsWith('.md')) {
          // 尝试从 markdown 中提取配置
          const content = fs.readFileSync(filePath, 'utf-8');
          const jsonMatch = content.match(/```json\n([\s\S]*?)\n```/);
          if (jsonMatch) {
            config = { ...config, ...JSON.parse(jsonMatch[1]) };
          }
          // 提取 name 行
          const nameMatch = content.match(/^name:\s*(.+)$/m);
          if (nameMatch) {
            config.name = nameMatch[1].trim();
          }
        } else {
          // .js 文件，尝试加载
          delete require.cache[require.resolve(filePath)];
          const mod = require(filePath);
          config = typeof mod === 'function' ? mod() : mod;
        }

        agents.push({
          name: config.name || baseName,
          role: config.role || '-',
          description: config.description || '-',
          file: entry.name,
        });
      } catch (err) {
        agents.push({
          name: baseName,
          role: '-',
          description: `Error loading: ${err.message}`,
          file: entry.name,
        });
      }
    }
  }

  if (agents.length === 0) {
    console.log('No agents found in .agent/agents/');
    return;
  }

  console.log(`\nFound ${agents.length} agent(s) in .agent/agents/:\n`);
  console.log('Name              Role                Description');
  console.log('----------------  ------------------  ------------------------------------------');

  for (const agent of agents) {
    const name = (agent.name || '').padEnd(16).slice(0, 16);
    const role = (agent.role || '-').padEnd(18).slice(0, 18);
    const desc = (agent.description || '-').slice(0, 40);
    console.log(`${name}  ${role}  ${desc}`);
  }

  console.log('');
}

module.exports = { listCommand };
