#!/usr/bin/env node

// Test session persistence features
const { TradingViewAutomation } = require('./lib/tradingview-automation')

async function testSessionPersistence() {
  console.log('🧪 Testing TradingView session persistence...')
  
  const automation = new TradingViewAutomation()
  
  try {
    // Initialize automation
    await automation.init()
    
    // Check session info before login
    console.log('\n📊 Session info before login:')
    const sessionBefore = await automation.getSessionInfo()
    console.log(JSON.stringify(sessionBefore, null, 2))
    
    // Try to login (will skip if already logged in)
    console.log('\n🔐 Testing login with session persistence...')
    const loginResult = await automation.login()
    
    if (loginResult) {
      console.log('✅ Login successful!')
      
      // Check session info after login
      console.log('\n📊 Session info after login:')
      const sessionAfter = await automation.getSessionInfo()
      console.log(JSON.stringify(sessionAfter, null, 2))
      
      // Take a screenshot to verify we're logged in
      await automation.navigateToChart({ symbol: 'BTCUSD', timeframe: '5' })
      const screenshot = await automation.takeScreenshot('session_test.png')
      console.log(`📸 Screenshot saved: ${screenshot}`)
      
    } else {
      console.log('❌ Login failed')
    }
    
  } catch (error) {
    console.error('❌ Test failed:', error)
  } finally {
    // Close automation (this will save session)
    await automation.close()
    console.log('✅ Automation closed and session saved')
  }
}

// Run the test
testSessionPersistence()
  .then(() => {
    console.log('\n🎉 Session persistence test completed!')
    process.exit(0)
  })
  .catch((error) => {
    console.error('💥 Test failed:', error)
    process.exit(1)
  })
