#!/usr/bin/env node

/**
 * Test script to demonstrate session persistence and captcha avoidance
 * This script shows how to use saved sessions to avoid "are you human" checks
 */

import { TradingViewAutomation } from './lib/tradingview-automation.js'

async function testSessionPersistenceWithCaptchaAvoidance() {
  console.log('🚀 Testing TradingView Session Persistence (Captcha Avoidance)')
  console.log('=' * 60)
  
  const automation = new TradingViewAutomation()
  
  try {
    // Initialize with stealth features
    await automation.init()
    console.log('✅ Browser initialized with anti-detection features')
    
    // Test existing session data
    console.log('\n📊 Testing existing session data...')
    const sessionTest = await automation.testSessionPersistence()
    
    if (sessionTest.hasSessionData && sessionTest.isValid) {
      console.log('🎉 Valid session found! No login required.')
      console.log('✨ This avoids any captcha challenges!')
      
      // Navigate to chart to demonstrate functionality
      console.log('\n📈 Navigating to chart...')
      const chartSuccess = await automation.navigateToChart({
        symbol: 'SOLUSD',
        timeframe: '5'
      })
      
      if (chartSuccess) {
        console.log('✅ Successfully navigated to chart using saved session')
        
        // Take a screenshot to prove it works
        const screenshot = await automation.takeScreenshot('session_success.png')
        console.log(`📸 Screenshot saved: ${screenshot}`)
      }
      
    } else if (sessionTest.hasSessionData && !sessionTest.isValid) {
      console.log('⚠️ Saved session data exists but appears expired')
      console.log('🔄 Session needs to be refreshed')
      
      // Clear expired session
      await automation.clearSession()
      console.log('🗑️ Cleared expired session data')
      
      // Use smart login for manual authentication
      console.log('\n🔐 Using smart login (manual intervention required)...')
      const loginSuccess = await automation.smartLogin()
      
      if (loginSuccess) {
        console.log('✅ New session saved! Future runs will avoid captcha.')
      }
      
    } else {
      console.log('📝 No saved session found - first time setup required')
      console.log('🔐 Using smart login (manual intervention required)...')
      
      const loginSuccess = await automation.smartLogin()
      
      if (loginSuccess) {
        console.log('✅ New session saved! Future runs will avoid captcha.')
        
        // Navigate to chart to demonstrate functionality
        console.log('\n📈 Navigating to chart...')
        const chartSuccess = await automation.navigateToChart({
          symbol: 'SOLUSD',
          timeframe: '5'
        })
        
        if (chartSuccess) {
          console.log('✅ Successfully navigated to chart')
          
          // Take a screenshot
          const screenshot = await automation.takeScreenshot('first_login_success.png')
          console.log(`📸 Screenshot saved: ${screenshot}`)
        }
      } else {
        console.log('❌ Manual login was not completed in time')
      }
    }
    
    // Show final session info
    console.log('\n📋 Final session status:')
    const finalInfo = await automation.getSessionInfo()
    console.log(JSON.stringify(finalInfo, null, 2))
    
  } catch (error) {
    console.error('❌ Test failed:', error)
    
    // Take debug screenshot
    try {
      await automation.takeScreenshot('session_test_error.png')
    } catch (e) {
      console.error('Could not take error screenshot:', e)
    }
  } finally {
    // Clean up
    await automation.close()
    console.log('\n🧹 Cleanup completed')
  }
}

// Instructions for manual setup
function showInstructions() {
  console.log('\n📋 SETUP INSTRUCTIONS FOR CAPTCHA AVOIDANCE:')
  console.log('=' * 50)
  console.log('1. Run this script for the first time')
  console.log('2. When prompted, manually log in to TradingView in the browser window')
  console.log('3. The script will detect the login and save the session')
  console.log('4. Future runs will use the saved session and avoid captchas!')
  console.log('5. Sessions are saved in: .tradingview-session/')
  console.log('\n💡 TIP: Run this periodically to refresh the session and keep it valid')
  console.log('\n🚀 Starting test...\n')
}

if (import.meta.url === `file://${process.argv[1]}`) {
  showInstructions()
  testSessionPersistenceWithCaptchaAvoidance()
    .then(() => {
      console.log('\n✅ Session persistence test completed!')
      process.exit(0)
    })
    .catch((error) => {
      console.error('\n❌ Session persistence test failed:', error)
      process.exit(1)
    })
}

export { testSessionPersistenceWithCaptchaAvoidance }
