/**
 * OAuth-then-Brainstorm Flow
 * 1. Shows OAuth URL
 * 2. Waits for user authorization
 * 3. Automatically proceeds with brainstorming
 */

const qwenClient = require('./qwen-client.js');
const { multiAIBrainstorm } = require('./brainstorm-orchestrator.js');

async function oauthThenBrainstorm(topic, options = {}) {
  try {
    // Step 1: Initialize client
    const isInitialized = await qwenClient.initialize();

    if (isInitialized && qwenClient.isAuthenticated()) {
      console.log('\n✓ Already authenticated with Qwen OAuth!');
      console.log('✓ Proceeding with brainstorming...\n');
      await multiAIBrainstorm(topic, options);
      return;
    }

    // Step 2: Perform OAuth flow
    console.log('\n🔐 Qwen OAuth Authentication Required\n');
    console.log('='.repeat(70));

    await qwenClient.performOAuthFlow();

    // Step 3: Verify authentication worked
    if (!qwenClient.isAuthenticated()) {
      throw new Error('OAuth authentication failed');
    }

    console.log('\n✓ Authentication successful!');
    console.log('✓ Proceeding with brainstorming...\n');

    // Step 4: Run brainstorming
    await multiAIBrainstorm(topic, options);

  } catch (error) {
    console.error('\n❌ Error:', error.message);
    console.error('\nTroubleshooting:');
    console.error('- Make sure you clicked "Authorize" in the browser');
    console.error('- Check your internet connection');
    console.error('- The OAuth URL may have expired (try again)\n');
    throw error;
  }
}

// Export for use
module.exports = { oauthThenBrainstorm };

// If run directly
if (require.main === module) {
  const topic = process.argv[2] || 'test topic';
  oauthThenBrainstorm(topic).catch(console.error);
}
