import type { Prompter } from './prompts.js';
import type { ConfigBuilder } from './config.js';
import { renderSummary } from './summary.js';
import { setupProviders } from './providers.js';
import { setupChannels } from './channels.js';
import { setupMemory } from './memory.js';
import { setupAutomation } from './automation.js';
import { setupSecurity } from './security.js';
import { setupGateway } from './gateway.js';

const MENU_OPTIONS = [
  { label: 'Model Providers', value: 'providers' },
  { label: 'Channels', value: 'channels' },
  { label: 'Memory', value: 'memory' },
  { label: 'Automation', value: 'automation' },
  { label: 'Security', value: 'security' },
  { label: 'Gateway', value: 'gateway' },
];

const SECTION_HANDLERS: Record<string, (p: Prompter, b: ConfigBuilder) => Promise<void>> = {
  providers: setupProviders,
  channels: setupChannels,
  memory: setupMemory,
  automation: setupAutomation,
  security: setupSecurity,
  gateway: setupGateway,
};

export async function runMenu(p: Prompter, builder: ConfigBuilder): Promise<void> {
  while (true) {
    p.println();
    p.println('Flynn Setup — Current Configuration');
    p.println(renderSummary(builder.build()));
    p.println();
    p.println('What would you like to configure?');
    for (let i = 0; i < MENU_OPTIONS.length; i++) {
      p.println(`  ${i + 1}. ${MENU_OPTIONS[i].label}`);
    }
    p.println('  0. Done — save and exit');

    const answer = await p.ask('>', '0');
    const idx = parseInt(answer, 10);

    if (idx === 0 || isNaN(idx)) {break;}
    if (idx >= 1 && idx <= MENU_OPTIONS.length) {
      const section = MENU_OPTIONS[idx - 1].value;
      const handler = SECTION_HANDLERS[section];
      if (handler) {
        p.println();
        await handler(p, builder);
      }
    }
  }
}

export async function runFirstRunWizard(p: Prompter): Promise<ConfigBuilder> {
  const { ConfigBuilder } = await import('./config.js');

  p.println();
  p.println("Let's get Flynn running. This takes about 2 minutes.");
  p.println();

  const builder = new ConfigBuilder();

  // Step 1: Model provider
  await setupProviders(p, builder);

  // Step 2: Channels
  p.println();
  await setupChannels(p, builder);

  return builder;
}
