#!/usr/bin/env node

/**
 * Test script for the dual-session enhanced screenshot service
 * Uses API calls instead of direct imports for Docker compatibility
 */

async function testDualSessionScreenshots() {
  console.log('🚀 Testing Enhanced Screenshot Service with Dual Sessions (API)')
  
  try {
    // Test configuration
    const config = {
      symbol: 'SOLUSD',
      timeframe: '240',
      layouts: ['ai', 'diy'],
      analyze: true // Request AI analysis of both screenshots
    }
    
    console.log('📋 Test Configuration:', config)
    
    // Test API endpoint availability
    console.log('\n🔍 Checking API endpoint...')
    const healthResponse = await fetch('http://localhost:3000/api/enhanced-screenshot')
    if (!healthResponse.ok) {
      throw new Error(`API endpoint not available: ${healthResponse.status}`)
    }
    const healthData = await healthResponse.json()
    console.log('✅ API endpoint available:', healthData.message)
    
    // Perform the dual-session screenshot capture via API
    console.log('\n🔄 Starting dual-session capture via API...')
    const startTime = Date.now()
    
    const response = await fetch('http://localhost:3000/api/enhanced-screenshot', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(config)
    })
    
    const endTime = Date.now()
    const duration = (endTime - startTime) / 1000
    
    if (!response.ok) {
      const errorData = await response.json()
      throw new Error(`API request failed: ${errorData.error || response.statusText}`)
    }
    
    const result = await response.json()
    
    console.log('\n✅ Capture completed!')
    console.log(`⏱️ Duration: ${duration.toFixed(2)} seconds`)
    console.log(`📸 Screenshots captured: ${result.screenshots?.length || 0}`)
    
    if (result.screenshots) {
      result.screenshots.forEach((screenshot, index) => {
        console.log(`   ${index + 1}. ${screenshot}`)
      })
    }
    
    if (result.screenshots?.length === 2) {
      console.log('\n🎯 SUCCESS: Both AI and DIY layouts captured successfully!')
    } else {
      console.log('\n⚠️ WARNING: Expected 2 screenshots, got', result.screenshots?.length || 0)
      if (result.errors) {
        console.log('📋 Errors encountered:')
        result.errors.forEach((error, index) => {
          console.log(`   ${index + 1}. ${error}`)
        })
      }
    }

    // Display AI analysis results if available
    if (result.analysis) {
      console.log('\n🤖 AI Analysis Results:')
      console.log(`   📊 Market Sentiment: ${result.analysis.marketSentiment}`)
      console.log(`   📈 Recommendation: ${result.analysis.recommendation}`)
      console.log(`   🎯 Confidence: ${result.analysis.confidence}%`)
      
      // Trading Setup Section
      if (result.analysis.entry) {
        console.log('\n💰 TRADING SETUP:')
        console.log(`   � Entry: $${result.analysis.entry.price}${result.analysis.entry.buffer ? ' ' + result.analysis.entry.buffer : ''}`)
        if (result.analysis.entry.rationale) {
          console.log(`      💡 ${result.analysis.entry.rationale}`)
        }
      }
      
      if (result.analysis.stopLoss) {
        console.log(`   🛑 Stop Loss: $${result.analysis.stopLoss.price}`)
        if (result.analysis.stopLoss.rationale) {
          console.log(`      💡 ${result.analysis.stopLoss.rationale}`)
        }
      }
      
      // Enhanced Take Profit Display
      if (result.analysis.takeProfits) {
        console.log('\n🎯 TAKE PROFIT TARGETS:')
        if (result.analysis.takeProfits.tp1) {
          const tp1 = result.analysis.takeProfits.tp1
          console.log(`   🥉 TP1: $${tp1.price}`)
          console.log(`      📋 ${tp1.description}`)
          if (tp1.rsiExpectation) {
            console.log(`      📊 RSI: ${tp1.rsiExpectation}`)
          }
          if (tp1.obvExpectation) {
            console.log(`      📈 OBV: ${tp1.obvExpectation}`)
          }
        }
        if (result.analysis.takeProfits.tp2) {
          const tp2 = result.analysis.takeProfits.tp2
          console.log(`   🥈 TP2: $${tp2.price}`)
          console.log(`      📋 ${tp2.description}`)
          if (tp2.rsiExpectation) {
            console.log(`      📊 RSI: ${tp2.rsiExpectation}`)
          }
          if (tp2.obvExpectation) {
            console.log(`      📈 OBV: ${tp2.obvExpectation}`)
          }
        }
      }
      
      if (result.analysis.riskToReward) {
        console.log(`\n⚖️  Risk/Reward: ${result.analysis.riskToReward}`)
      }
      
      if (result.analysis.confirmationTrigger) {
        console.log(`\n🔔 Confirmation Trigger: ${result.analysis.confirmationTrigger}`)
      }
      
      // Timeframe Risk Assessment
      if (result.analysis.timeframeRisk) {
        console.log('\n⏰ TIMEFRAME RISK ASSESSMENT:')
        if (result.analysis.timeframeRisk.assessment) {
          console.log(`   📊 Risk Level: ${result.analysis.timeframeRisk.assessment}`)
        }
        if (result.analysis.timeframeRisk.positionSize) {
          console.log(`   � Position Size: ${result.analysis.timeframeRisk.positionSize}`)
        }
        if (result.analysis.timeframeRisk.leverageRecommendation) {
          console.log(`   🎚️  Leverage: ${result.analysis.timeframeRisk.leverageRecommendation}`)
        }
      }
      
      // Key Levels
      if (result.analysis.keyLevels) {
        console.log('\n📊 KEY LEVELS:')
        if (result.analysis.keyLevels.resistance?.length > 0) {
          console.log(`   �🔴 Resistance: ${result.analysis.keyLevels.resistance.map(r => `$${r}`).join(', ')}`)
        }
        if (result.analysis.keyLevels.support?.length > 0) {
          console.log(`   🟢 Support: ${result.analysis.keyLevels.support.map(s => `$${s}`).join(', ')}`)
        }
      }
      
      // Indicator Analysis
      if (result.analysis.indicatorAnalysis) {
        console.log('\n📈 TECHNICAL INDICATORS:')
        if (result.analysis.indicatorAnalysis.rsi) {
          console.log(`   📊 RSI: ${result.analysis.indicatorAnalysis.rsi}`)
        }
        if (result.analysis.indicatorAnalysis.vwap) {
          console.log(`   📈 VWAP: ${result.analysis.indicatorAnalysis.vwap}`)
        }
        if (result.analysis.indicatorAnalysis.obv) {
          console.log(`   📊 OBV: ${result.analysis.indicatorAnalysis.obv}`)
        }
        if (result.analysis.indicatorAnalysis.macd) {
          console.log(`   📉 MACD: ${result.analysis.indicatorAnalysis.macd}`)
        }
      }
      
      // Layout Comparison
      if (result.analysis.layoutComparison) {
        console.log('\n🔄 LAYOUT COMPARISON:')
        if (result.analysis.layoutComparison.aiLayout) {
          console.log(`   🤖 AI Layout: ${result.analysis.layoutComparison.aiLayout}`)
        }
        if (result.analysis.layoutComparison.diyLayout) {
          console.log(`   🔧 DIY Layout: ${result.analysis.layoutComparison.diyLayout}`)
        }
        if (result.analysis.layoutComparison.consensus) {
          console.log(`   ✅ Consensus: ${result.analysis.layoutComparison.consensus}`)
        }
        if (result.analysis.layoutComparison.divergences) {
          console.log(`   ⚠️  Divergences: ${result.analysis.layoutComparison.divergences}`)
        }
      }
      
      // Alternatives
      if (result.analysis.alternatives) {
        console.log('\n🔄 ALTERNATIVES:')
        if (result.analysis.alternatives.tigherStopOption) {
          console.log(`   🎯 Tighter Stop: ${result.analysis.alternatives.tigherStopOption}`)
        }
        if (result.analysis.alternatives.scaledEntry) {
          console.log(`   📊 Scaled Entry: ${result.analysis.alternatives.scaledEntry}`)
        }
        if (result.analysis.alternatives.invalidationScenario) {
          console.log(`   ❌ Invalidation: ${result.analysis.alternatives.invalidationScenario}`)
        }
      }
    } else {
      console.log('\n⚠️ No AI analysis results received')
    }
    
    // Test summary
    console.log('\n📊 Test Summary:')
    console.log(`   • API Response: ${response.ok ? 'Success' : 'Failed'}`)
    console.log(`   • Duration: ${duration.toFixed(2)}s`)
    console.log(`   • Screenshots: ${result.screenshots?.length || 0}/2`)
    console.log(`   • Success Rate: ${((result.screenshots?.length || 0) / 2 * 100).toFixed(0)}%`)
    
  } catch (error) {
    console.error('\n❌ Test failed:', error.message)
    console.error('Stack trace:', error.stack)
    process.exit(1)
  }
}

// Run the test
if (require.main === module) {
  // Add fetch for Node.js environments that don't have it built-in
  if (typeof fetch === 'undefined') {
    const { default: fetch } = require('node-fetch')
    global.fetch = fetch
  }
  
  testDualSessionScreenshots()
    .then(() => {
      console.log('\n🎉 All tests completed successfully!')
      process.exit(0)
    })
    .catch((error) => {
      console.error('\n💥 Test suite failed:', error)
      process.exit(1)
    })
}

module.exports = { testDualSessionScreenshots }
