#!/usr/bin/env node

/**
 * Test script for the new layout switching approach using keyboard shortcut '.'
 * This script tests the layouts dialog method for switching between AI and DIY layouts
 */

const fs = require('fs').promises
const path = require('path')

async function testLayoutsDialog() {
  console.log('🧪 Testing TradingView Layouts Dialog Method\n')
  
  try {
    // Load trading settings
    const settingsPath = path.join(__dirname, 'trading-settings.json')
    const settings = JSON.parse(await fs.readFile(settingsPath, 'utf8'))
    
    console.log('📋 Current Settings:')
    console.log(`   Symbol: ${settings.symbol}`)
    console.log(`   Timeframe: ${settings.timeframe} (${settings.timeframe}min = ${settings.timeframe/60}h)`)
    console.log(`   Layouts: ${settings.layouts.join(', ')}`)
    console.log('')
    
    // Import TradingView automation using require for CommonJS
    const automation = require('./lib/tradingview-automation.ts')
    const tradingViewAutomation = automation.tradingViewAutomation
    
    console.log('🔧 Initializing browser...')
    await tradingViewAutomation.init()
    
    console.log('🔐 Checking login status...')
    const isLoggedIn = await tradingViewAutomation.isLoggedIn()
    
    if (!isLoggedIn) {
      console.log('⚠️  Not logged in - attempting smart login...')
      const loginSuccess = await tradingViewAutomation.smartLogin()
      
      if (!loginSuccess) {
        throw new Error('Login required for layout dialog test')
      }
    }
    
    console.log('🗺️  Navigating to chart...')
    const navSuccess = await tradingViewAutomation.navigateToChart({
      symbol: settings.symbol,
      timeframe: settings.timeframe,
      waitForChart: true
    })
    
    if (!navSuccess) {
      throw new Error('Failed to navigate to chart')
    }
    
    console.log('⏳ Waiting for chart data...')
    await tradingViewAutomation.waitForChartData()
    
    console.log('📸 Taking initial screenshot...')
    await tradingViewAutomation.takeScreenshot(`test_initial_layout_${Date.now()}.png`)
    
    // Test the layouts dialog approach
    console.log('\n🎛️  Testing Layouts Dialog Method')
    console.log('   Press "." to open layouts dialog, then click specific layouts\n')
    
    // Test each layout
    for (const layout of settings.layouts) {
      console.log(`📋 Testing ${layout.toUpperCase()} layout...`)
      
      const switchSuccess = await tradingViewAutomation.switchLayout(layout)
      console.log(`   Switch attempt: ${switchSuccess ? '✅' : '❌'}`)
      
      if (switchSuccess) {
        console.log(`   ⏳ Waiting for ${layout} layout to load...`)
        const loadSuccess = await tradingViewAutomation.waitForLayoutLoad(layout)
        console.log(`   Load detection: ${loadSuccess ? '✅' : '❌'}`)
        
        // Take a test screenshot
        const testScreenshot = `test_${layout}_layout_dialog_${Date.now()}.png`
        console.log(`   📸 Taking test screenshot: ${testScreenshot}`)
        await tradingViewAutomation.takeScreenshot(testScreenshot)
        
        console.log(`   ✅ ${layout} layout test completed\n`)
      } else {
        console.log(`   ❌ Failed to switch to ${layout} layout\n`)
      }
      
      // Wait between layout switches
      await new Promise(resolve => setTimeout(resolve, 2000))
    }
    
    console.log('✅ Layouts dialog test completed successfully!')
    console.log('\n📸 Check the screenshots/ directory for test images')
    console.log('🐛 Check debug screenshots for troubleshooting if needed')
    
  } catch (error) {
    console.error('❌ Layouts dialog test failed:', error.message)
    
    if (error.message.includes('CAPTCHA') || error.message.includes('manual intervention')) {
      console.log('\n💡 CAPTCHA detected - this is expected in Docker environment')
      console.log('   The manual CAPTCHA handling workflow should have been triggered')
    }
    
    if (error.message.includes('layout')) {
      console.log('\n🔧 Layout dialog issues detected:')
      console.log('   - Check if layouts dialog opens when pressing "." key')
      console.log('   - Verify AI and DIY layouts are available in the dialog')
      console.log('   - Check debug screenshots for dialog appearance')
    }
  }
}

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

module.exports = { testLayoutsDialog }
