import type { Prompter } from './prompts.js';
import type { ConfigBuilder } from './config.js';

const EMBEDDING_PROVIDERS = [
  { label: 'OpenAI (recommended)', value: 'openai' },
  { label: 'Gemini', value: 'gemini' },
  { label: 'Ollama (local)', value: 'ollama' },
  { label: 'Voyage AI', value: 'voyage' },
];

const REUSABLE_PROVIDERS = ['openai', 'gemini'];

export async function setupMemory(p: Prompter, builder: ConfigBuilder): Promise<void> {
  p.println('  Vector search enables semantic memory — Flynn remembers and retrieves');
  p.println('  information based on meaning, not just keywords.');
  const enable = await p.confirm('Enable vector search for semantic memory?', false);
  if (!enable) {return;}

  p.println('  Pick a provider to generate embeddings (vector representations of text).');
  p.println('  If you already configured OpenAI or Gemini as a model, you can reuse that key.');
  const provider = await p.choose('Embedding provider:', EMBEDDING_PROVIDERS);

  const config = builder.build();
  const modelApiKey = findReusableApiKey(config, provider);

  let apiKey: string | undefined;
  if (REUSABLE_PROVIDERS.includes(provider) && modelApiKey) {
    const reuse = await p.confirm('Reuse API key from model provider?', true);
    apiKey = reuse ? modelApiKey : await p.password('API key');
  } else if (provider !== 'ollama') {
    apiKey = await p.password('API key');
  }

  builder.setMemoryEmbedding({
    provider,
    api_key: apiKey,
    endpoint: provider === 'ollama' ? 'http://localhost:11434' : undefined,
  });
  p.println('✓ Vector search enabled');
}

function findReusableApiKey(config: Record<string, any>, embeddingProvider: string): string | undefined {
  const models = config.models ?? {};
  for (const tier of ['default', 'fast', 'complex', 'local']) {
    const m = models[tier];
    if (m?.provider === embeddingProvider && m?.api_key) {return m.api_key;}
  }
  return undefined;
}
