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

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

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

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

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

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

        proc.stderr.on('data', (chunk) => {
          ctx.stream({ type: 'codex-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 });
        });
      });
    },
  },
};
