/**
 * AI Integration Usage Examples
 * 
 * This script demonstrates how to use the AI-powered task management endpoints
 * in various scenarios.
 */

const API_BASE = 'http://localhost:3000/api/ai';

/**
 * Example 1: Create a task from natural language
 */
async function createTaskExample() {
  console.log('=== Creating Task from Natural Language ===');
  
  try {
    const response = await fetch(`${API_BASE}/create-task`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        prompt: 'Implement user authentication with JWT tokens and password reset functionality',
        projectId: 'ecommerce-platform',
        context: {
          projectDescription: 'Modern e-commerce platform built with React and Node.js',
          currentTasks: [
            'Database schema design',
            'API endpoint structure',
            'Frontend component library'
          ],
          completedTasks: [
            'Project initialization',
            'Development environment setup',
            'CI/CD pipeline'
          ],
          userRole: 'full-stack developer'
        }
      })
    });

    const result = await response.json();
    
    if (result.success) {
      console.log('✅ Task created successfully:');
      console.log(`   Title: ${result.data.title}`);
      console.log(`   Priority: ${result.data.priority}`);
      console.log(`   Complexity: ${result.data.complexity}`);
      console.log(`   Estimated Hours: ${result.data.estimatedHours}`);
      console.log(`   Tags: ${result.data.tags?.join(', ')}`);
      console.log('   Acceptance Criteria:');
      result.data.acceptanceCriteria?.forEach((criteria, index) => {
        console.log(`   ${index + 1}. ${criteria}`);
      });
      
      return result.data;
    } else {
      console.error('❌ Failed to create task:', result.error);
    }
  } catch (error) {
    console.error('❌ Request failed:', error.message);
  }
}

/**
 * Example 2: Break down a complex task into subtasks
 */
async function breakdownTaskExample() {
  console.log('\n=== Breaking Down Complex Task ===');
  
  try {
    const taskId = 'auth-system-task-123';
    const response = await fetch(`${API_BASE}/breakdown/${taskId}`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        taskDescription: 'Implement complete user authentication system with JWT tokens, password reset, email verification, and role-based access control',
        context: 'Node.js Express API with PostgreSQL database, React frontend, using industry security best practices'
      })
    });

    const result = await response.json();
    
    if (result.success) {
      console.log('✅ Task breakdown completed:');
      console.log(`   Main Task: ${result.data.title}`);
      console.log(`   Complexity: ${result.data.complexity}`);
      console.log(`   Total Estimated Hours: ${result.data.estimatedTotalHours}`);
      console.log('   Subtasks:');
      
      result.data.subtasks.forEach((subtask, index) => {
        console.log(`   ${index + 1}. ${subtask.title} (${subtask.estimatedHours}h)`);
        console.log(`      ${subtask.description}`);
      });
      
      if (result.data.suggestedApproach) {
        console.log(`   Suggested Approach: ${result.data.suggestedApproach}`);
      }
      
      return result.data;
    } else {
      console.error('❌ Failed to break down task:', result.error);
    }
  } catch (error) {
    console.error('❌ Request failed:', error.message);
  }
}

/**
 * Example 3: Get AI-powered task suggestions
 */
async function getTaskSuggestionsExample() {
  console.log('\n=== Getting Task Suggestions ===');
  
  try {
    const projectId = 'ecommerce-platform';
    const params = new URLSearchParams({
      projectDescription: 'Modern e-commerce platform with real-time features',
      completedTasks: 'User authentication,Product catalog,Shopping cart',
      currentTasks: 'Payment integration,Order management',
      goals: 'Launch MVP,Scale to 10k users,Mobile app'
    });

    const response = await fetch(`${API_BASE}/suggestions/${projectId}?${params}`);
    const result = await response.json();
    
    if (result.success) {
      console.log('✅ Task suggestions generated:');
      console.log(`   Project: ${projectId}`);
      
      result.data.forEach((suggestion, index) => {
        console.log(`\n   ${index + 1}. ${suggestion.title} (Priority: ${suggestion.priority})`);
        console.log(`      ${suggestion.description}`);
        console.log(`      Rationale: ${suggestion.rationale}`);
        console.log(`      Confidence: ${(suggestion.confidence * 100).toFixed(1)}%`);
        if (suggestion.estimatedHours) {
          console.log(`      Estimated Hours: ${suggestion.estimatedHours}`);
        }
      });
      
      return result.data;
    } else {
      console.error('❌ Failed to get suggestions:', result.error);
    }
  } catch (error) {
    console.error('❌ Request failed:', error.message);
  }
}

/**
 * Example 4: Update task context with feedback
 */
async function updateTaskContextExample() {
  console.log('\n=== Updating Task Context with Feedback ===');
  
  try {
    const taskId = 'auth-system-task-123';
    const response = await fetch(`${API_BASE}/update-context/${taskId}`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        feedback: 'Task needs to include two-factor authentication (2FA) support and integration with OAuth providers like Google and GitHub. Security requirements are more stringent than initially specified.'
      })
    });

    const result = await response.json();
    
    if (result.success) {
      console.log('✅ Task context updated successfully');
      console.log('   Feedback has been recorded for future AI interactions');
    } else {
      console.error('❌ Failed to update context:', result.error);
    }
  } catch (error) {
    console.error('❌ Request failed:', error.message);
  }
}

/**
 * Example 5: Monitor AI service health and usage
 */
async function monitoringExample() {
  console.log('\n=== Monitoring AI Services ===');
  
  try {
    // Check service health
    const healthResponse = await fetch(`${API_BASE}/health`);
    const health = await healthResponse.json();
    
    console.log('🔍 Service Health Status:');
    console.log(`   Overall Health: ${health.healthy ? '✅ Healthy' : '❌ Degraded'}`);
    console.log(`   OpenAI: ${health.services.openai ? '✅' : '❌'}`);
    console.log(`   LangChain: ${health.services.langchain ? '✅' : '❌'}`);
    console.log(`   Redis Cache: ${health.services.redis ? '✅' : '❌'}`);
    console.log(`   Rate Limiter: ${health.services.rateLimiter ? '✅' : '❌'}`);
    
    // Get usage statistics
    const usageResponse = await fetch(`${API_BASE}/usage`);
    const usage = await usageResponse.json();
    
    console.log('\n📊 Usage Statistics:');
    console.log(`   Total Requests: ${usage.data.openai.requestCount}`);
    console.log(`   Tokens Used: ${usage.data.openai.totalTokensUsed.toLocaleString()}`);
    console.log(`   Estimated Cost: $${usage.data.openai.estimatedCost.toFixed(4)}`);
    console.log(`   AI Contexts Saved: ${usage.data.totalContextsSaved}`);
    
    if (usage.data.cacheHitRate !== undefined) {
      console.log(`   Cache Hit Rate: ${(usage.data.cacheHitRate * 100).toFixed(1)}%`);
    }
    
  } catch (error) {
    console.error('❌ Monitoring request failed:', error.message);
  }
}

/**
 * Example 6: Test AI service connections
 */
async function testConnectionsExample() {
  console.log('\n=== Testing AI Service Connections ===');
  
  try {
    const response = await fetch(`${API_BASE}/test-connection`, {
      method: 'POST'
    });
    
    const result = await response.json();
    
    if (result.success) {
      console.log('🧪 Connection Test Results:');
      console.log(`   OpenAI: ${result.connections.openai ? '✅ Connected' : '❌ Failed'}`);
      console.log(`   LangChain: ${result.connections.langchain ? '✅ Connected' : '❌ Failed'}`);
      console.log(`   Status: ${result.message}`);
    } else {
      console.error('❌ Connection test failed:', result.error);
    }
  } catch (error) {
    console.error('❌ Request failed:', error.message);
  }
}

/**
 * Example 7: Warm cache for better performance
 */
async function warmCacheExample() {
  console.log('\n=== Warming Cache for Better Performance ===');
  
  try {
    const response = await fetch(`${API_BASE}/warm-cache`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        projectId: 'ecommerce-platform'
      })
    });

    const result = await response.json();
    
    if (result.success) {
      console.log('🔥 Cache warming initiated');
      console.log(`   Project: ${result.projectId}`);
      console.log('   Common queries will be pre-cached for faster responses');
    } else {
      console.error('❌ Failed to warm cache:', result.error);
    }
  } catch (error) {
    console.error('❌ Request failed:', error.message);
  }
}

/**
 * Example 8: Complete workflow - Create, breakdown, and get suggestions
 */
async function completeWorkflowExample() {
  console.log('\n=== Complete AI Workflow Example ===');
  
  try {
    // Step 1: Create a task from natural language
    console.log('Step 1: Creating task from natural language...');
    const task = await createTaskFromPrompt(
      'Build a real-time notification system with email, SMS, and push notification support'
    );
    
    if (!task) return;
    
    // Step 2: Break down the task
    console.log('\nStep 2: Breaking down the task...');
    const breakdown = await breakdownTask(task.id, task.description);
    
    // Step 3: Get related suggestions
    console.log('\nStep 3: Getting related task suggestions...');
    await getRelatedSuggestions('notification-system-project');
    
    // Step 4: Provide feedback
    console.log('\nStep 4: Providing feedback...');
    await provideFeedback(task.id, 'Include notification preferences and user opt-out functionality');
    
    console.log('\n✅ Complete workflow finished successfully');
    
  } catch (error) {
    console.error('❌ Workflow failed:', error.message);
  }
}

// Helper functions for complete workflow
async function createTaskFromPrompt(prompt) {
  const response = await fetch(`${API_BASE}/create-task`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      prompt,
      projectId: 'notification-system-project',
      context: {
        projectDescription: 'Enterprise notification platform',
        userRole: 'backend developer'
      }
    })
  });
  
  const result = await response.json();
  return result.success ? { ...result.data, id: `task-${Date.now()}` } : null;
}

async function breakdownTask(taskId, description) {
  const response = await fetch(`${API_BASE}/breakdown/${taskId}`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      taskDescription: description,
      context: 'Node.js microservices architecture with message queues'
    })
  });
  
  const result = await response.json();
  if (result.success) {
    console.log(`   Created ${result.data.subtasks?.length || 0} subtasks`);
  }
  return result.success ? result.data : null;
}

async function getRelatedSuggestions(projectId) {
  const params = new URLSearchParams({
    projectDescription: 'Enterprise notification platform',
    completedTasks: 'Architecture design,Database setup',
    currentTasks: 'Notification system',
    goals: 'High availability,Scalability'
  });
  
  const response = await fetch(`${API_BASE}/suggestions/${projectId}?${params}`);
  const result = await response.json();
  
  if (result.success) {
    console.log(`   Generated ${result.data.length} task suggestions`);
  }
  
  return result.success ? result.data : null;
}

async function provideFeedback(taskId, feedback) {
  const response = await fetch(`${API_BASE}/update-context/${taskId}`, {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ feedback })
  });
  
  const result = await response.json();
  return result.success;
}

/**
 * Example 9: Error handling patterns
 */
async function errorHandlingExample() {
  console.log('\n=== Error Handling Examples ===');
  
  // Example of validation error
  try {
    console.log('Testing validation error...');
    const response = await fetch(`${API_BASE}/create-task`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        prompt: '', // Invalid: empty prompt
      })
    });
    
    const result = await response.json();
    if (!result.success && result.error === 'Validation error') {
      console.log('✅ Validation error handled correctly');
      console.log('   Details:', result.details[0].message);
    }
  } catch (error) {
    console.error('❌ Validation test failed:', error.message);
  }
  
  // Example of handling service unavailable
  try {
    console.log('\nTesting service health...');
    const response = await fetch(`${API_BASE}/health`);
    const result = await response.json();
    
    if (response.status === 503) {
      console.log('⚠️  AI services are degraded');
      console.log('   Implementing fallback behavior...');
      // Implement fallback logic here
    } else {
      console.log('✅ All AI services are operational');
    }
  } catch (error) {
    console.log('❌ Service completely unavailable - using offline mode');
    // Implement offline mode here
  }
}

/**
 * Main execution function
 */
async function runExamples() {
  console.log('🤖 AI Integration Usage Examples\n');
  console.log('This script demonstrates various AI-powered task management features.\n');
  
  try {
    // Run all examples
    await createTaskExample();
    await breakdownTaskExample();
    await getTaskSuggestionsExample();
    await updateTaskContextExample();
    await monitoringExample();
    await testConnectionsExample();
    await warmCacheExample();
    await errorHandlingExample();
    
    // Run complete workflow if all basic examples succeed
    await completeWorkflowExample();
    
    console.log('\n🎉 All examples completed successfully!');
    console.log('\nNext steps:');
    console.log('1. Integrate these patterns into your application');
    console.log('2. Set up monitoring and alerting');
    console.log('3. Configure rate limiting based on your usage patterns');
    console.log('4. Implement user feedback collection for continuous improvement');
    
  } catch (error) {
    console.error('\n❌ Examples failed:', error.message);
    console.log('\nTroubleshooting:');
    console.log('1. Make sure the API server is running on localhost:3000');
    console.log('2. Check that your OpenAI API key is configured');
    console.log('3. Verify Redis is running for caching features');
    console.log('4. Check the AI integration guide for setup instructions');
  }
}

// Export for use in other modules
if (typeof module !== 'undefined' && module.exports) {
  module.exports = {
    createTaskExample,
    breakdownTaskExample,
    getTaskSuggestionsExample,
    updateTaskContextExample,
    monitoringExample,
    testConnectionsExample,
    warmCacheExample,
    completeWorkflowExample,
    errorHandlingExample,
    runExamples
  };
}

// Run examples if script is executed directly
if (typeof require !== 'undefined' && require.main === module) {
  runExamples().catch(console.error);
}