#!/usr/bin/env node

/**
 * Test multi-layout functionality via API endpoints
 */

const https = require('https');
const http = require('http');

async function makeRequest(options, data) {
  return new Promise((resolve, reject) => {
    const protocol = options.port === 443 ? https : http;
    
    const req = protocol.request(options, (res) => {
      let body = '';
      res.on('data', (chunk) => {
        body += chunk;
      });
      res.on('end', () => {
        try {
          const parsed = JSON.parse(body);
          resolve({ status: res.statusCode, data: parsed });
        } catch (e) {
          resolve({ status: res.statusCode, data: body });
        }
      });
    });
    
    req.on('error', reject);
    
    if (data) {
      req.write(JSON.stringify(data));
    }
    
    req.end();
  });
}

async function testMultiLayoutAPI() {
  console.log('🌐 Testing Multi-Layout API Functionality\n');
  
  const baseURL = 'http://localhost:3000';
  
  try {
    console.log('1️⃣ Testing settings update to include multiple layouts...');
    
    // Update settings to include both AI and DIY layouts
    const settingsResponse = await makeRequest({
      hostname: 'localhost',
      port: 3000,
      path: '/api/settings',
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
    }, {
      symbol: 'SOLUSD',
      timeframe: '240',
      layouts: ['ai', 'diy']
    });
    
    console.log(`   Settings update status: ${settingsResponse.status}`);
    console.log(`   Response: ${JSON.stringify(settingsResponse.data, null, 2)}`);
    
    if (settingsResponse.status === 200) {
      console.log('   ✅ Settings updated successfully');
    } else {
      console.log('   ❌ Settings update failed');
      return;
    }
    
    console.log('\n2️⃣ Testing analysis with multiple layouts...');
    
    // Trigger analysis with multiple layouts
    const analysisResponse = await makeRequest({
      hostname: 'localhost',
      port: 3000,
      path: '/api/analyze',
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
    }, {
      symbol: 'SOLUSD',
      timeframe: '240',
      layouts: ['ai', 'diy'],
      useExisting: false
    });
    
    console.log(`   Analysis status: ${analysisResponse.status}`);
    console.log(`   Response: ${JSON.stringify(analysisResponse.data, null, 2)}`);
    
    if (analysisResponse.status === 200) {
      console.log('   ✅ Analysis completed successfully');
      
      const data = analysisResponse.data;
      if (data.screenshots && data.screenshots.length > 0) {
        console.log(`   📸 Screenshots captured: ${data.screenshots.length}`);
        data.screenshots.forEach((screenshot, index) => {
          console.log(`      ${index + 1}. ${screenshot}`);
        });
        
        // Check if we have screenshots for both layouts
        const hasAI = data.screenshots.some(s => s.includes('_ai_'));
        const hasDIY = data.screenshots.some(s => s.includes('_diy_'));
        
        console.log(`   🤖 AI layout screenshot: ${hasAI ? '✅' : '❌'}`);
        console.log(`   🔧 DIY layout screenshot: ${hasDIY ? '✅' : '❌'}`);
        
        if (hasAI && hasDIY) {
          console.log('   🎉 Multi-layout capture successful!');
        }
      }
      
      if (data.layoutsAnalyzed) {
        console.log(`   🎛️ Layouts analyzed: ${data.layoutsAnalyzed.join(', ')}`);
      }
      
    } else {
      console.log('   ❌ Analysis failed');
      if (analysisResponse.data.error) {
        console.log(`   Error: ${analysisResponse.data.error}`);
      }
    }
    
    console.log('\n3️⃣ Testing automated analysis with multiple layouts...');
    
    // Test automated analysis endpoint
    const automatedResponse = await makeRequest({
      hostname: 'localhost',
      port: 3000,
      path: '/api/automated-analysis',
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
    }, {
      symbol: 'SOLUSD',
      timeframe: '240',
      layouts: ['ai', 'diy'],
      mode: 'capture_with_config'
    });
    
    console.log(`   Automated analysis status: ${automatedResponse.status}`);
    console.log(`   Response: ${JSON.stringify(automatedResponse.data, null, 2)}`);
    
    if (automatedResponse.status === 200) {
      console.log('   ✅ Automated analysis completed successfully');
    } else {
      console.log('   ❌ Automated analysis failed');
    }
    
  } catch (error) {
    console.error('\n❌ API test failed:');
    console.error(error.message);
    
    if (error.code === 'ECONNREFUSED') {
      console.log('\n💡 Make sure the Next.js server is running:');
      console.log('   npm run dev');
      console.log('   or');
      console.log('   docker-compose up');
    }
  }
}

async function main() {
  console.log('🔬 Multi-Layout API Test Suite');
  console.log('==============================\n');
  
  await testMultiLayoutAPI();
  
  console.log('\n🏁 API test suite completed');
}

main().catch(error => {
  console.error('API test suite failed:', error);
  process.exit(1);
});
