import type { WizardPrompter } from '../prompter/interface.js';
import type { WizardState } from '../types.js';
import { detectProviderType } from '../constants.js';

/**
 * Provider setup stage — collects the user's LLM API key and detects the
 * provider type from the key prefix.
 *
 * In headless mode, reads from `MOSAIC_ANTHROPIC_API_KEY` or `MOSAIC_OPENAI_API_KEY`.
 */
export async function providerSetupStage(p: WizardPrompter, state: WizardState): Promise<void> {
  const isHeadless = process.env['MOSAIC_ASSUME_YES'] === '1' || !process.stdin.isTTY;

  if (isHeadless) {
    const anthropicKey = process.env['MOSAIC_ANTHROPIC_API_KEY'] ?? '';
    const openaiKey = process.env['MOSAIC_OPENAI_API_KEY'] ?? '';
    const key = anthropicKey || openaiKey;
    state.providerKey = key || undefined;
    state.providerType = detectProviderType(key);
    return;
  }

  p.separator();
  p.note(
    'Configure your LLM provider so the agent has a brain.\n' +
      'Anthropic (Claude) and OpenAI are supported.\n' +
      'You can skip this and add a key later via `mosaic configure`.',
    'LLM Provider',
  );

  const key = await p.text({
    message: 'API key (paste your Anthropic or OpenAI key, or press Enter to skip)',
    defaultValue: '',
    placeholder: 'sk-ant-api03-... or sk-...',
  });

  if (key) {
    const provider = detectProviderType(key);
    state.providerKey = key;
    state.providerType = provider;

    if (provider === 'anthropic') {
      p.log('Detected provider: Anthropic (Claude)');
    } else if (provider === 'openai') {
      p.log('Detected provider: OpenAI');
    } else {
      p.log('Provider auto-detection failed. Key will be stored as ANTHROPIC_API_KEY.');
      state.providerType = 'anthropic';
    }
  } else {
    state.providerType = 'none';
    p.log('No API key provided. You can add one later with `mosaic configure`.');
  }
}
