#!/usr/bin/env node

/**
 * Scalp Preset: Parallel Multi-Timeframe Screenshot Capture
 * Uses API calls with intelligent batching for all scalping timeframes
 */

// Scalping-focused timeframes 
const SCALP_PRESET = {
  name: 'Scalp Preset',
  timeframes: [
    { name: '1m', tv: '1', description: 'Ultra-short scalping' },
    { name: '3m', tv: '3', description: 'Short scalping' },
    { name: '5m', tv: '5', description: 'Standard scalping' },
    { name: '15m', tv: '15', description: 'Swing scalping' },
    { name: '30m', tv: '30', description: 'Longer scalping' },
    { name: '1h', tv: '60', description: 'Context timeframe' },
    { name: '4h', tv: '240', description: 'Trend context' }
  ]
}

async function testScalpPresetParallel() {
  console.log('🚀 SCALP PRESET: Parallel Multi-Timeframe Capture')
  console.log('⚡ Testing the most efficient screenshot capture for scalping')
  
  const symbol = 'SOLUSD'
  const layouts = ['ai', 'diy']
  
  console.log('\n📋 Configuration:')
  console.log(`   📊 Symbol: ${symbol}`)
  console.log(`   ⏱️ Timeframes: ${SCALP_PRESET.timeframes.length} (${SCALP_PRESET.timeframes.map(tf => tf.name).join(', ')})`)
  console.log(`   🎨 Layouts: ${layouts.length} (${layouts.join(', ')})`)
  console.log(`   📸 Total Screenshots: ${SCALP_PRESET.timeframes.length * layouts.length}`)
  
  try {
    console.log('\n🔄 Starting parallel capture of all timeframes...')
    const startTime = Date.now()
    
    // Create parallel promises for each timeframe
    const capturePromises = SCALP_PRESET.timeframes.map(async (tf, index) => {
      const timeframeName = tf.name
      const timeframeValue = tf.tv
      
      try {
        console.log(`📸 [${index + 1}/${SCALP_PRESET.timeframes.length}] Starting ${timeframeName} (${timeframeValue})...`)
        
        const response = await fetch('http://localhost:9001/api/enhanced-screenshot', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            symbol: symbol,
            timeframe: timeframeValue,
            layouts: layouts,
            analyze: false // Skip AI analysis for speed testing
          })
        })
        
        if (!response.ok) {
          throw new Error(`API request failed: ${response.status} ${response.statusText}`)
        }
        
        const result = await response.json()
        
        if (result.success && result.screenshots) {
          console.log(`✅ ${timeframeName}: Captured ${result.screenshots.length}/${layouts.length} screenshots`)
          return {
            timeframe: timeframeName,
            timeframeValue: timeframeValue,
            success: true,
            screenshots: result.screenshots,
            sessionId: result.sessionId
          }
        } else {
          throw new Error(result.error || 'Unknown API error')
        }
        
      } catch (error) {
        console.error(`❌ ${timeframeName}: Failed - ${error.message}`)
        return {
          timeframe: timeframeName,
          timeframeValue: timeframeValue,
          success: false,
          error: error.message
        }
      }
    })
    
    // Wait for all timeframes to complete
    console.log('\n⏳ Waiting for all parallel captures to complete...')
    const results = await Promise.all(capturePromises)
    
    const endTime = Date.now()
    const duration = (endTime - startTime) / 1000
    
    // Analyze results
    const successful = results.filter(r => r.success)
    const failed = results.filter(r => !r.success)
    const totalScreenshots = successful.reduce((sum, r) => sum + (r.screenshots?.length || 0), 0)
    
    console.log('\n✅ PARALLEL CAPTURE COMPLETED!')
    console.log(`⏱️ Total Duration: ${duration.toFixed(2)} seconds`)
    console.log(`📸 Screenshots Captured: ${totalScreenshots}/${SCALP_PRESET.timeframes.length * layouts.length}`)
    console.log(`🎯 Timeframes Successful: ${successful.length}/${SCALP_PRESET.timeframes.length}`)
    console.log(`🚀 Average Speed: ${(totalScreenshots / duration).toFixed(1)} screenshots/second`)
    
    // Success breakdown
    console.log('\n📊 DETAILED RESULTS:')
    SCALP_PRESET.timeframes.forEach(tf => {
      const result = results.find(r => r.timeframe === tf.name)
      if (result) {
        if (result.success) {
          console.log(`   ✅ ${tf.name.padEnd(4)} (${tf.tv.padEnd(3)}): ${result.screenshots.length} screenshots`)
          result.screenshots.forEach(screenshot => {
            console.log(`      📁 ${screenshot}`)
          })
        } else {
          console.log(`   ❌ ${tf.name.padEnd(4)} (${tf.tv.padEnd(3)}): ${result.error}`)
        }
      }
    })
    
    // Performance analysis
    const successRate = (successful.length / SCALP_PRESET.timeframes.length * 100).toFixed(1)
    console.log(`\n📈 SUCCESS RATE: ${successRate}%`)
    
    if (successful.length === SCALP_PRESET.timeframes.length) {
      console.log('🎉 PERFECT SUCCESS: All scalping timeframes captured!')
    } else if (successful.length > 0) {
      console.log(`⚠️ PARTIAL SUCCESS: ${successful.length}/${SCALP_PRESET.timeframes.length} timeframes completed`)
    } else {
      console.log('❌ COMPLETE FAILURE: No timeframes captured successfully')
    }
    
    // Efficiency metrics
    console.log('\n⚡ EFFICIENCY ANALYSIS:')
    console.log(`   • Parallel timeframes: ${SCALP_PRESET.timeframes.length}`)
    console.log(`   • Average time per timeframe: ${(duration / SCALP_PRESET.timeframes.length).toFixed(2)}s`)
    console.log(`   • Screenshots per timeframe: ${layouts.length}`)
    console.log(`   • Time saved vs sequential: ~${((SCALP_PRESET.timeframes.length * 30) - duration).toFixed(0)}s`)
    
    if (failed.length > 0) {
      console.log('\n❌ FAILED TIMEFRAMES:')
      failed.forEach(f => {
        console.log(`   • ${f.timeframe}: ${f.error}`)
      })
    }
    
    console.log('\n🎯 SCALP PRESET TEST COMPLETED!')
    
  } catch (error) {
    console.error('\n❌ Scalp preset test failed:', error.message)
    console.error('Stack trace:', error.stack)
    process.exit(1)
  }
}

// Run the test
console.log('🎯 Starting Scalp Preset Parallel Screenshot Test...')
testScalpPresetParallel()
