/**
 * Multi-AI Brainstorm Orchestrator
 * Coordinates multiple specialized AI agents for collaborative brainstorming
 */

const qwenClient = require('./qwen-client.js');

/**
 * Agent System Prompts
 */
const AGENT_SYSTEM_PROMPTS = {
  content: `You are an expert Content Specialist and Copywriter. Your role is to provide insights on content creation, messaging, and communication strategies.

Focus on:
- Content tone and voice
- Audience engagement
- Content structure and flow
- Clarity and persuasiveness
- Brand storytelling

Provide practical, actionable content insights.`,

  seo: `You are an expert SEO Specialist with deep knowledge of search engine optimization, content strategy, and digital marketing.

Focus on:
- Keyword research and strategy
- On-page and technical SEO
- Content optimization for search
- Link building and authority
- SEO performance metrics
- Competitor SEO analysis

Provide specific, data-driven SEO recommendations.`,

  smm: `You are an expert Social Media Manager specializing in multi-platform content strategies, community engagement, and viral marketing.

Focus on:
- Platform-specific content strategies (LinkedIn, Twitter, Instagram, TikTok, etc.)
- Content calendars and scheduling
- Community building and engagement
- Influencer collaboration strategies
- Social media analytics and KPIs
- Viral content mechanics

Provide actionable social media marketing insights.`,

  pm: `You are an expert Product Manager with extensive experience in product strategy, PRD creation, roadmap planning, and stakeholder management.

Focus on:
- Product vision and strategy
- Feature prioritization frameworks
- User personas and use cases
- Go-to-market strategies
- Success metrics and KPIs
- Agile development processes
- Stakeholder communication

Provide structured product management insights.`,

  code: `You are an expert Software Architect specializing in backend logic, system design, algorithms, and technical implementation.

Focus on:
- System architecture and design patterns
- Algorithm design and optimization
- API design and integration
- Database design and optimization
- Security best practices
- Scalability and performance
- Technology stack recommendations

Provide concrete technical implementation guidance.`,

  design: `You are a world-class UI/UX Designer with deep expertise in user research, interaction design, visual design systems, and modern design tools.

Focus on:
- User research and persona development
- Information architecture and navigation
- Visual design systems (color, typography, spacing)
- Interaction design and micro-interactions
- Design trends and best practices
- Accessibility and inclusive design
- Design tools and deliverables

Provide specific, actionable UX recommendations.`,

  web: `You are an expert Frontend Developer specializing in responsive web design, modern JavaScript frameworks, and web performance optimization.

Focus on:
- Modern frontend frameworks (React, Vue, Angular, Svelte)
- Responsive design and mobile-first approach
- Web performance optimization
- CSS strategies (Tailwind, CSS-in-JS, styled-components)
- Component libraries and design systems
- Progressive Web Apps
- Browser compatibility

Provide practical frontend development insights.`,

  app: `You are an expert Mobile App Developer specializing in iOS and Android development, React Native, Flutter, and mobile-first design patterns.

Focus on:
- Mobile app architecture (native vs cross-platform)
- Platform-specific best practices (iOS, Android)
- Mobile UI/UX patterns
- Performance optimization for mobile
- App store optimization (ASO)
- Mobile-specific constraints and opportunities
- Push notifications and engagement

Provide actionable mobile development insights.`
};

/**
 * Available agents
 */
const AVAILABLE_AGENTS = Object.keys(AGENT_SYSTEM_PROMPTS);

/**
 * Brainstorm orchestrator class
 */
class BrainstormOrchestrator {
  constructor() {
    this.agents = AVAILABLE_AGENTS;
  }

  /**
   * Validate agent selection
   */
  validateAgents(selectedAgents) {
    if (!selectedAgents || selectedAgents.length === 0) {
      return this.agents; // Return all agents if none specified
    }

    const valid = selectedAgents.filter(agent => this.agents.includes(agent));
    const invalid = selectedAgents.filter(agent => !this.agents.includes(agent));

    if (invalid.length > 0) {
      console.warn(`⚠️  Unknown agents ignored: ${invalid.join(', ')}`);
    }

    return valid.length > 0 ? valid : this.agents;
  }

  /**
   * Generate brainstorming prompt for a specific agent
   */
  generateAgentPrompt(topic, agent) {
    const systemPrompt = AGENT_SYSTEM_PROMPTS[agent];

    return `# Brainstorming Request

**Topic**: ${topic}

**Your Role**: ${agent.toUpperCase()} Specialist

**Instructions**:
1. Analyze this topic from your ${agent} perspective
2. Provide 3-5 unique insights or recommendations
3. Be specific and actionable
4. Consider opportunities, challenges, and best practices
5. Think creatively but stay grounded in practical reality

Format your response as clear bullet points or numbered lists.
`;
  }

  /**
   * Execute brainstorming with multiple agents
   */
  async brainstorm(topic, options = {}) {
    const {
      agents = [],
      concurrency = 3
    } = options;

    const selectedAgents = this.validateAgents(agents);
    const results = {};

    console.log(`\n🧠 Multi-AI Brainstorming Session`);
    console.log(`📝 Topic: ${topic}`);
    console.log(`👥 Agents: ${selectedAgents.map(a => a.toUpperCase()).join(', ')}`);
    console.log(`\n⏳ Gathering insights...\n`);

    // Process agents in batches for controlled concurrency
    for (let i = 0; i < selectedAgents.length; i += concurrency) {
      const batch = selectedAgents.slice(i, i + concurrency);

      const batchPromises = batch.map(async (agent) => {
        try {
          const userPrompt = this.generateAgentPrompt(topic, agent);
          const messages = [
            { role: 'system', content: AGENT_SYSTEM_PROMPTS[agent] },
            { role: 'user', content: userPrompt }
          ];

          const response = await qwenClient.chatCompletion(messages, {
            temperature: 0.8,
            maxTokens: 1000
          });

          return { agent, response, success: true };
        } catch (error) {
          return { agent, error: error.message, success: false };
        }
      });

      const batchResults = await Promise.all(batchPromises);

      for (const result of batchResults) {
        if (result.success) {
          results[result.agent] = result.response;
          console.log(`✓ ${result.agent.toUpperCase()} Agent: Insights received`);
        } else {
          console.error(`✗ ${result.agent.toUpperCase()} Agent: ${result.error}`);
          results[result.agent] = `[Error: ${result.error}]`;
        }
      }
    }

    return {
      topic,
      agents: selectedAgents,
      results,
      timestamp: new Date().toISOString()
    };
  }

  /**
   * Format brainstorming results for display
   */
  formatResults(brainstormData) {
    let output = `\n${'='.repeat(60)}\n`;
    output += `🧠 MULTI-AI BRAINSTORM RESULTS\n`;
    output += `${'='.repeat(60)}\n\n`;
    output += `📝 Topic: ${brainstormData.topic}\n`;
    output += `👥 Agents: ${brainstormData.agents.map(a => a.toUpperCase()).join(', ')}\n`;
    output += `🕐 ${new Date(brainstormData.timestamp).toLocaleString()}\n\n`;

    for (const agent of brainstormData.agents) {
      const response = brainstormData.results[agent];
      output += `${'─'.repeat(60)}\n`;
      output += `🤖 ${agent.toUpperCase()} AGENT INSIGHTS\n`;
      output += `${'─'.repeat(60)}\n\n`;
      output += `${response}\n\n`;
    }

    output += `${'='.repeat(60)}\n`;
    output += `✨ Brainstorming complete! Use these insights to inform your project.\n`;

    return output;
  }

  /**
   * List available agents
   */
  listAgents() {
    console.log('\n🤖 Available AI Agents:\n');

    const agentDescriptions = {
      content: 'Copywriting & Communication',
      seo: 'Search Engine Optimization',
      smm: 'Social Media Marketing',
      pm: 'Product Management',
      code: 'Software Architecture',
      design: 'UI/UX Design',
      web: 'Frontend Development',
      app: 'Mobile Development'
    };

    for (const agent of this.agents) {
      const desc = agentDescriptions[agent] || '';
      console.log(`  • ${agent.padEnd(10)} - ${desc}`);
    }
    console.log('');
  }
}

/**
 * Main brainstorm function
 */
async function multiAIBrainstorm(topic, options = {}) {
  // Initialize client
  const isInitialized = await qwenClient.initialize();

  if (!isInitialized || !qwenClient.isAuthenticated()) {
    console.log('\n🔐 Multi-AI Brainstorm requires Qwen API authentication\n');
    await qwenClient.promptForCredentials();
  }

  const orchestrator = new BrainstormOrchestrator();

  if (options.listAgents) {
    orchestrator.listAgents();
    return;
  }

  // Execute brainstorming
  const results = await orchestrator.brainstorm(topic, options);
  const formatted = orchestrator.formatResults(results);

  console.log(formatted);

  return results;
}

module.exports = {
  multiAIBrainstorm,
  BrainstormOrchestrator,
  AVAILABLE_AGENTS
};
