/**
 * Cursor Agent
 * Handles: cursor-query
 * Spawns the Cursor Agent CLI and streams output.
 */
import { spawn } from 'child_process';
import os from 'os';

export default {
  name: 'cursor',
  actions: {
    'cursor-query': async (params, ctx) => {
      const { command, options } = params;
      const resolveBinary = ctx.resolveBinary || ((name) => name);

      return new Promise((resolve) => {
        const args = [];
        if (options?.model) args.push('--model', options.model);

        const proc = spawn(resolveBinary('cursor-agent'), [...args, command || ''], {
          shell: true,
          cwd: options?.projectPath || options?.cwd || os.homedir(),
          env: process.env,
        });

        if (ctx.trackProcess) ctx.trackProcess(ctx.requestId, { proc, action: 'cursor-query' });

        proc.stdout.on('data', (chunk) => {
          ctx.stream({ type: 'cursor-response', content: chunk.toString() });
        });

        proc.stderr.on('data', (chunk) => {
          ctx.stream({ type: 'cursor-error', content: chunk.toString() });
        });

        proc.on('close', (code) => {
          if (ctx.untrackProcess) ctx.untrackProcess(ctx.requestId);
          resolve({ exitCode: code });
        });

        proc.on('error', () => {
          if (ctx.untrackProcess) ctx.untrackProcess(ctx.requestId);
          resolve({ exitCode: 1 });
        });
      });
    },
  },
};
