import type { WizardPrompter } from '../prompter/interface.js';
import type { WizardState, RuntimeName } from '../types.js';
import { detectRuntime, type RuntimeInfo } from '../runtime/detector.js';
import { formatInstallInstructions } from '../runtime/installer.js';
import { configureMcpForRuntime } from '../runtime/mcp-config.js';

const RUNTIME_NAMES: RuntimeName[] = ['claude', 'codex', 'opencode', 'pi'];

export async function runtimeSetupStage(p: WizardPrompter, state: WizardState): Promise<void> {
  p.separator();

  const spin = p.spinner();
  spin.update('Detecting installed runtimes...');

  const runtimes: RuntimeInfo[] = RUNTIME_NAMES.map(detectRuntime);

  spin.stop('Runtime detection complete');

  const detected = runtimes.filter((r) => r.installed);
  const notDetected = runtimes.filter((r) => !r.installed);

  if (detected.length > 0) {
    const summary = detected
      .map((r) => `  ${r.label}: ${r.version ?? 'installed'} (${r.path ?? 'unknown'})`)
      .join('\n');
    p.note(summary, 'Detected Runtimes');
  } else {
    p.warn('No runtimes detected. Install at least one to use Mosaic.');
  }

  state.runtimes.detected = detected.map((r) => r.name);

  // Offer installation info for missing runtimes in advanced mode
  if (state.mode === 'advanced' && notDetected.length > 0) {
    const showInstall = await p.confirm({
      message: `${notDetected.length.toString()} runtime(s) not found. Show install instructions?`,
      initialValue: false,
    });

    if (showInstall) {
      for (const rt of notDetected) {
        p.note(formatInstallInstructions(rt.name), `Install ${rt.label}`);
      }
    }
  }

  // Configure MCP sequential-thinking for detected runtimes
  if (detected.length > 0) {
    const spin2 = p.spinner();
    spin2.update('Configuring sequential-thinking MCP...');
    try {
      for (const rt of detected) {
        configureMcpForRuntime(rt.name);
      }
      spin2.stop('MCP sequential-thinking configured');
      state.runtimes.mcpConfigured = true;
    } catch (err) {
      spin2.stop('MCP configuration failed (non-fatal)');
      p.warn(
        `MCP setup failed: ${err instanceof Error ? err.message : String(err)}. Run 'mosaic seq fix' later.`,
      );
    }
  }
}
