validateApiKey method

Future<bool> validateApiKey()

Implementation

Future<bool> validateApiKey() async {
  if (apiKey != null && apiKey!.isNotEmpty) {
    return true;
  }

  logger.info('');
  logger.info('${lightCyan.wrap('OpenAI API key required')}');
  logger.info('');
  logger.info(
      'Get your API key from: ${lightCyan.wrap('https://platform.openai.com/api-keys')}');
  logger.info('');

  try {
    final key = Input(
      prompt: 'Enter your OpenAI API key',
      validator: (value) {
        if (value.isEmpty) return false;
        if (!value.startsWith('sk-')) return false;
        return true;
      },
    ).interact();

    _cachedApiKey = key;

    final shouldSave = Confirm(
      prompt: 'Save API key to ~/.pubmind/config.json for future use?',
      defaultValue: true,
    ).interact();

    if (shouldSave) {
      final saved = CommandsHelper.saveApiKeyToConfig(key);
      if (saved) {
        logger.success('API key saved successfully!');
      } else {
        logger.warn('Failed to save API key to config file');
      }
    }

    logger.info('');
    return true;
  } catch (e) {
    logger.err('Failed to get API key: $e');
    return false;
  }
}