import type { Flow, Step, StepContext } from '../types.js';

const q = (ctx: StepContext) => String(ctx.input.question);

/**
 * Parallel research flow — dispatches 3 research agents simultaneously,
 * then synthesizes the result on the first one to complete.
 */
export const parallelResearch: Flow = {
  name: 'parallel-research',
  description: 'Research from 3 angles in parallel, synthesize results on first completion',
  steps: [
    {
      id: 'angle-web',
      kind: 'agent',
      agent: 'research-analyst',
      run: (ctx) =>
        `Research the following question from a web / prior-art perspective:\n\n${q(ctx)}`,
    },
    {
      id: 'angle-code',
      kind: 'agent',
      agent: 'codebase-explorer',
      deps: [],
      run: (ctx) =>
        `Research the following question from a codebase analysis perspective:\n\n${q(ctx)}`,
    },
    {
      id: 'angle-security',
      kind: 'agent',
      agent: 'adversarial-security-analyst',
      deps: [],
      run: (ctx) =>
        `Research the following question from a security perspective:\n\n${q(ctx)}`,
    },
    {
      id: 'synthesize',
      kind: 'code',
      deps: ['angle-web', 'angle-code', 'angle-security'],
      trigger_rule: 'one_success',
      run: (ctx) => {
        const web = ctx.results['angle-web'];
        const code = ctx.results['angle-code'];
        const security = ctx.results['angle-security'];
        const parts = [
          '# Parallel Research Synthesis',
          '',
          web ? `## Web Angle\n${web}` : '## Web Angle\n*(not yet completed)*',
          code ? `## Code Angle\n${code}` : '## Code Angle\n*(not yet completed)*',
          security ? `## Security Angle\n${security}` : '## Security Angle\n*(not yet completed)*',
        ];
        return parts.join('\n\n');
      },
    },
  ],
  render: (ctx) => {
    return ctx.results['synthesize'] ?? 'No synthesis produced.';
  },
};
