#!/usr/bin/env node

/**
 * Test script for comprehensive tech stack recommendations integration
 * Tests the new endpoint that combines Claude AI, template-based, and domain-based recommendations
 */

const axios = require('axios');

const UNIFIED_SERVICE_URL = 'http://localhost:8013';
const COMPREHENSIVE_ENDPOINT = '/api/unified/comprehensive-recommendations';

// Test data matching the frontend request structure
const testRequest = {
  template: {
    id: 'test-template-123',
    title: 'E-commerce Platform',
    description: 'A comprehensive e-commerce solution',
    category: 'E-commerce',
    type: 'web-app'
  },
  features: [
    {
      id: 'feature-1',
      name: 'User Authentication',
      description: 'Secure user login and registration system',
      feature_type: 'essential',
      complexity: 'medium',
      business_rules: ['Users must verify email', 'Password must meet security requirements'],
      technical_requirements: ['JWT tokens', 'Password hashing', 'Email verification']
    },
    {
      id: 'feature-2',
      name: 'Product Catalog',
      description: 'Product listing and search functionality',
      feature_type: 'essential',
      complexity: 'medium',
      business_rules: ['Products must have valid pricing', 'Search must be fast'],
      technical_requirements: ['Database indexing', 'Search optimization']
    },
    {
      id: 'feature-3',
      name: 'Payment Processing',
      description: 'Secure payment handling',
      feature_type: 'essential',
      complexity: 'high',
      business_rules: ['PCI compliance required', 'Multiple payment methods'],
      technical_requirements: ['SSL encryption', 'Payment gateway integration']
    }
  ],
  businessContext: {
    questions: [
      {
        question: 'What is your target audience?',
        answer: 'Small to medium businesses selling products online'
      },
      {
        question: 'What is your expected user volume?',
        answer: 'We expect around 10,000 users initially, growing to 100,000 within a year'
      },
      {
        question: 'What are your security requirements?',
        answer: 'High security requirements due to handling payment information and customer data'
      },
      {
        question: 'What is your budget range?',
        answer: 'Budget is around $15,000 for initial development and infrastructure'
      }
    ]
  },
  projectName: 'E-commerce Platform',
  projectType: 'E-commerce',
  templateId: 'test-template-123',
  budget: 15000,
  domain: 'ecommerce',
  includeClaude: true,
  includeTemplateBased: true,
  includeDomainBased: true
};

async function testComprehensiveRecommendations() {
  console.log('🧪 Testing Comprehensive Tech Stack Recommendations Integration');
  console.log('=' .repeat(60));
  
  // Check if service is running
  try {
    const healthResponse = await axios.get(`${UNIFIED_SERVICE_URL}/health`, { timeout: 5000 });
    console.log('✅ Unified service is running');
    console.log(`   Status: ${healthResponse.data.status}`);
    console.log(`   Version: ${healthResponse.data.version}`);
  } catch (error) {
    console.log('❌ Unified service is not running or not accessible');
    console.log('   Make sure to start the service with: npm start');
    console.log('   Service should be running on port 8013');
    return;
  }
  
  try {
    console.log('📡 Making request to unified service...');
    console.log(`URL: ${UNIFIED_SERVICE_URL}${COMPREHENSIVE_ENDPOINT}`);
    console.log(`Template: ${testRequest.template.title}`);
    console.log(`Features: ${testRequest.features.length}`);
    console.log(`Business Questions: ${testRequest.businessContext.questions.length}`);
    console.log('');

    const response = await axios.post(
      `${UNIFIED_SERVICE_URL}${COMPREHENSIVE_ENDPOINT}`,
      testRequest,
      {
        timeout: 60000, // 60 seconds timeout
        headers: {
          'Content-Type': 'application/json'
        }
      }
    );

    console.log('✅ Response received successfully!');
    console.log('📊 Response Status:', response.status);
    console.log('📈 Response Structure:');
    console.log('');

    // Analyze response structure
    const data = response.data;
    
    if (data.success) {
      console.log('✅ Success: true');
      console.log('📝 Message:', data.message);
      console.log('');
      
      // Check Claude recommendations
      if (data.data.claude?.success) {
        console.log('🤖 Claude AI Recommendations: ✅ Available');
        if (data.data.claude.data?.claude_recommendations) {
          const claudeRecs = data.data.claude.data.claude_recommendations;
          console.log('   - Frontend:', claudeRecs.technology_recommendations?.frontend?.framework || 'N/A');
          console.log('   - Backend:', claudeRecs.technology_recommendations?.backend?.framework || 'N/A');
          console.log('   - Database:', claudeRecs.technology_recommendations?.database?.primary || 'N/A');
        }
      } else {
        console.log('🤖 Claude AI Recommendations: ❌ Failed');
        console.log('   Error:', data.data.claude?.error || 'Unknown error');
        if (data.data.claude?.error === 'Claude API key not configured') {
          console.log('   💡 To enable Claude AI recommendations:');
          console.log('      1. Get your API key from: https://console.anthropic.com/');
          console.log('      2. Add CLAUDE_API_KEY=your_key_here to .env file');
          console.log('      3. Restart the service');
        }
      }
      
      // Check template-based recommendations
      if (data.data.templateBased?.success) {
        console.log('📊 Template-based Recommendations: ✅ Available');
        console.log('   - Permutations:', data.data.templateBased.data?.permutations?.success ? '✅' : '❌');
        console.log('   - Combinations:', data.data.templateBased.data?.combinations?.success ? '✅' : '❌');
      } else {
        console.log('📊 Template-based Recommendations: ❌ Failed');
        console.log('   Error:', data.data.templateBased?.error || 'Unknown error');
      }
      
      // Check domain-based recommendations
      if (data.data.domainBased?.success) {
        console.log('🏢 Domain-based Recommendations: ✅ Available');
        console.log('   - Recommendations Count:', data.data.domainBased.data?.data?.recommendations?.length || 0);
      } else {
        console.log('🏢 Domain-based Recommendations: ❌ Failed');
        console.log('   Error:', data.data.domainBased?.error || 'Unknown error');
      }
      
      // Check unified recommendations
      if (data.data.unified) {
        console.log('🔗 Unified Recommendations: ✅ Available');
        console.log('   - Approach:', data.data.unified.approach || 'N/A');
        console.log('   - Confidence:', data.data.unified.confidence || 'N/A');
        console.log('   - Tech Stacks Count:', data.data.unified.techStacks?.length || 0);
      }
      
      // Check analysis
      if (data.data.analysis) {
        console.log('📈 Analysis: ✅ Available');
        console.log('   - Comprehensive Score:', data.data.analysis.comparison?.comprehensiveScore || 'N/A');
        console.log('   - Recommendation Quality:', data.data.analysis.comparison?.recommendationQuality || 'N/A');
      }
      
    } else {
      console.log('❌ Success: false');
      console.log('Error:', data.error || 'Unknown error');
    }

  } catch (error) {
    console.log('❌ Test failed!');
    console.log('Error:', error.message);
    
    if (error.response) {
      console.log('Response Status:', error.response.status);
      console.log('Response Data:', JSON.stringify(error.response.data, null, 2));
    } else if (error.request) {
      console.log('No response received. Is the unified service running?');
      console.log('Make sure to start the service with: npm start');
    }
  }
  
  console.log('');
  console.log('🏁 Test completed');
}

// Run the test
if (require.main === module) {
  testComprehensiveRecommendations().catch(console.error);
}

module.exports = { testComprehensiveRecommendations };
