/**
 * Detect Agent
 * Handles: detect-agents
 * Checks which AI CLI agents are installed on the local machine.
 */
import { execSync } from 'child_process';
import fs from 'fs';
import path from 'path';

const AGENT_DEFINITIONS = [
  { name: 'claude', binary: 'claude', label: 'Claude Code' },
  { name: 'codex', binary: 'codex', label: 'OpenAI Codex' },
  { name: 'cursor', binary: 'cursor-agent', label: 'Cursor Agent' },
];

export default {
  name: 'detect',
  actions: {
    'detect-agents': async (params, ctx) => {
      const isWindows = process.platform === 'win32';
      const whichCmd = isWindows ? 'where' : 'which';
      const localBinDir = ctx.localBinDir || null;

      const agents = {};
      for (const agent of AGENT_DEFINITIONS) {
        try {
          const result = execSync(`${whichCmd} ${agent.binary}`, {
            stdio: 'pipe',
            timeout: 5000,
          }).toString().trim();
          agents[agent.name] = {
            installed: true,
            path: result.split('\n')[0].trim(),
            label: agent.label,
          };
        } catch {
          // Check local node_modules/.bin as fallback
          if (localBinDir) {
            const localPath = path.join(localBinDir, agent.binary + (isWindows ? '.cmd' : ''));
            if (fs.existsSync(localPath)) {
              agents[agent.name] = { installed: true, path: localPath, label: agent.label };
              continue;
            }
          }
          agents[agent.name] = { installed: false, label: agent.label };
        }
      }
      return { agents };
    },
  },
};
