import type { WizardPrompter } from '../prompter/interface.js';
import type { ConfigService } from '../config/config-service.js';
import type { WizardState } from '../types.js';
import { DEFAULTS } from '../constants.js';
import { providerSetupStage } from './provider-setup.js';
import { runtimeSetupStage } from './runtime-setup.js';
import { hooksPreviewStage } from './hooks-preview.js';
import { skillsSelectStage } from './skills-select.js';
import { finalizeStage } from './finalize.js';
import { gatewayConfigStage } from './gateway-config.js';
import { gatewayBootstrapStage } from './gateway-bootstrap.js';

export interface QuickStartOptions {
  skipGateway?: boolean;
  gatewayHost?: string;
  gatewayPort?: number;
  gatewayPortOverride?: number;
  skipGatewayNpmInstall?: boolean;
}

/**
 * Quick Start path — minimal questions to get a working agent.
 *
 * 1. Provider API key
 * 2. Admin email + password (via gateway bootstrap)
 * 3. Everything else uses defaults.
 *
 * Target: under 90 seconds for a returning user.
 */
export async function quickStartPath(
  prompter: WizardPrompter,
  state: WizardState,
  configService: ConfigService,
  options: QuickStartOptions,
): Promise<void> {
  state.mode = 'quick';

  // 1. Provider setup (first question)
  await providerSetupStage(prompter, state);

  // Apply sensible defaults for everything else
  state.soul.agentName ??= 'Mosaic';
  state.soul.roleDescription ??= DEFAULTS.roleDescription;
  state.soul.communicationStyle ??= 'direct';
  state.user.background = DEFAULTS.background;
  state.user.accessibilitySection = DEFAULTS.accessibilitySection;
  state.user.personalBoundaries = DEFAULTS.personalBoundaries;
  state.tools.gitProviders = [];
  state.tools.credentialsLocation = DEFAULTS.credentialsLocation;
  state.tools.customToolsSection = DEFAULTS.customToolsSection;

  // Runtime detection (auto, no user input in quick mode)
  await runtimeSetupStage(prompter, state);

  // Hooks (auto-accept in quick mode for Claude)
  await hooksPreviewStage(prompter, state);

  // Skills (recommended set, no user input in quick mode)
  await skillsSelectStage(prompter, state);

  // Finalize (writes configs, links runtime assets, syncs skills)
  await finalizeStage(prompter, state, configService);

  // Gateway config + bootstrap
  if (!options.skipGateway) {
    const headlessRun = process.env['MOSAIC_ASSUME_YES'] === '1' || !process.stdin.isTTY;

    try {
      const configResult = await gatewayConfigStage(prompter, state, {
        host: options.gatewayHost ?? 'localhost',
        defaultPort: options.gatewayPort ?? 14242,
        portOverride: options.gatewayPortOverride,
        skipInstall: options.skipGatewayNpmInstall,
        providerKey: state.providerKey,
        providerType: state.providerType ?? 'none',
      });

      if (!configResult.ready || !configResult.host || !configResult.port) {
        if (headlessRun) {
          prompter.warn('Gateway configuration failed in headless mode — aborting wizard.');
          process.exit(1);
        }
      } else {
        const bootstrapResult = await gatewayBootstrapStage(prompter, state, {
          host: configResult.host,
          port: configResult.port,
        });
        if (!bootstrapResult.completed) {
          prompter.warn('Admin bootstrap failed — aborting wizard.');
          process.exit(1);
        }
      }
    } catch (err) {
      prompter.warn(`Gateway setup failed: ${err instanceof Error ? err.message : String(err)}`);
      throw err;
    }
  }
}
