/**
 * Test AI DCA Manager Functionality
 * 
 * Tests the AI-driven Dollar Cost Averaging system
 * that intelligently scales into positions when reversal potential is detected
 */

const AIDCAManager = require('./lib/ai-dca-manager').default

// Test DCA analysis with SOL position scenario (based on screenshot)
async function testDCAAnalysis() {
  console.log('🧪 Testing AI DCA Manager Analysis')
  console.log('=' .repeat(50))

  // Scenario: SOL-PERP long position from screenshot
  // Entry: $185.98, Current: $183.87 (1.13% drop - potential DCA opportunity)
  const testParams = {
    currentPosition: {
      side: 'long',
      size: 2.69, // SOL amount from screenshot
      entryPrice: 185.98,
      currentPrice: 183.87,
      unrealizedPnl: -6.73, // From screenshot (red, losing position)
      stopLoss: 181.485, // From screenshot
      takeProfit: 187.12 // From screenshot
    },
    accountStatus: {
      accountValue: 2789.44, // Max amount from screenshot
      availableBalance: 1500, // Estimated available
      leverage: 15.2, // Current leverage from screenshot
      liquidationPrice: 177.198 // From screenshot
    },
    marketData: {
      price: 183.87,
      priceChange24h: -6.75, // From screenshot (red, declining)
      volume: 245000000, // Estimated volume
      rsi: 32, // Oversold territory (estimated)
      support: 180.0, // Estimate based on recent lows
      resistance: 189.0 // Estimate based on recent highs
    },
    maxLeverageAllowed: 20
  }

  console.log('📊 Current Position Status:')
  console.log(`   Position: ${testParams.currentPosition.side.toUpperCase()} ${testParams.currentPosition.size} SOL`)
  console.log(`   Entry Price: $${testParams.currentPosition.entryPrice}`)
  console.log(`   Current Price: $${testParams.currentPosition.currentPrice}`)
  console.log(`   Unrealized PnL: $${testParams.currentPosition.unrealizedPnl.toFixed(2)}`)
  console.log(`   Current Leverage: ${testParams.accountStatus.leverage}x`)
  console.log(`   Stop Loss: $${testParams.currentPosition.stopLoss}`)
  console.log(`   Take Profit: $${testParams.currentPosition.takeProfit}`)
  console.log(`   Liquidation Price: $${testParams.accountStatus.liquidationPrice}`)
  console.log()

  // Test DCA analysis
  console.log('🔍 Running AI DCA Analysis...')
  const dcaResult = AIDCAManager.analyzeDCAOpportunity(testParams)

  console.log('📈 DCA Analysis Results:')
  console.log('=' .repeat(30))
  console.log(`   Should DCA: ${dcaResult.shouldDCA ? '✅ YES' : '❌ NO'}`)
  console.log(`   Confidence: ${dcaResult.confidence}%`)
  console.log(`   Risk Level: ${dcaResult.riskAssessment}`)
  console.log(`   Reasoning: ${dcaResult.reasoning}`)
  console.log()

  if (dcaResult.shouldDCA) {
    console.log('💰 DCA Execution Plan:')
    console.log('=' .repeat(25))
    console.log(`   DCA Amount: ${dcaResult.dcaAmount?.toFixed(4)} SOL`)
    console.log(`   New Average Price: $${dcaResult.newAveragePrice?.toFixed(4)}`)
    console.log(`   New Stop Loss: $${dcaResult.newStopLoss?.toFixed(4)}`)
    console.log(`   New Take Profit: $${dcaResult.newTakeProfit?.toFixed(4)}`)
    console.log(`   New Leverage: ${dcaResult.newLeverage?.toFixed(1)}x`)
    console.log(`   New Liquidation: $${dcaResult.newLiquidationPrice?.toFixed(4)}`)
    console.log()

    // Calculate potential impact
    const totalPositionAfterDCA = testParams.currentPosition.size + dcaResult.dcaAmount
    const originalPositionValue = testParams.currentPosition.size * testParams.currentPosition.entryPrice
    const dcaPositionValue = dcaResult.dcaAmount * testParams.currentPosition.currentPrice
    const totalInvested = originalPositionValue + dcaPositionValue
    const liquidationBuffer = Math.abs(dcaResult.newLiquidationPrice - dcaResult.newStopLoss) / dcaResult.newStopLoss * 100

    console.log('📊 Position Impact Analysis:')
    console.log('=' .repeat(30))
    console.log(`   Original Position: ${testParams.currentPosition.size} SOL @ $${testParams.currentPosition.entryPrice}`)
    console.log(`   DCA Addition: ${dcaResult.dcaAmount?.toFixed(4)} SOL @ $${testParams.currentPosition.currentPrice}`)
    console.log(`   Total Position: ${totalPositionAfterDCA.toFixed(4)} SOL`)
    console.log(`   Total Invested: $${totalInvested.toFixed(2)}`)
    console.log(`   Average Cost: $${dcaResult.newAveragePrice?.toFixed(4)}`)
    console.log(`   Liquidation Buffer: ${liquidationBuffer.toFixed(1)}% above stop loss`)
    console.log()

    // Calculate break-even scenarios
    const originalLoss = testParams.currentPosition.unrealizedPnl
    const breakEvenPrice = dcaResult.newAveragePrice
    const priceToBreakEven = ((breakEvenPrice - testParams.currentPosition.currentPrice) / testParams.currentPosition.currentPrice * 100)

    console.log('🎯 Break-Even Analysis:')
    console.log('=' .repeat(25))
    console.log(`   Current Loss: $${originalLoss.toFixed(2)}`)
    console.log(`   Break-Even Price: $${breakEvenPrice?.toFixed(4)}`)
    console.log(`   Price Move Needed: +${priceToBreakEven.toFixed(2)}% from current price`)
    console.log(`   Profit at Take Profit: $${((dcaResult.newTakeProfit - breakEvenPrice) * totalPositionAfterDCA).toFixed(2)}`)
  }

  console.log('\n🧠 AI Decision Logic:')
  console.log('=' .repeat(25))
  
  // Explain the AI reasoning
  const priceMovement = ((testParams.currentPosition.currentPrice - testParams.currentPosition.entryPrice) / testParams.currentPosition.entryPrice) * 100
  console.log(`   Price Movement: ${priceMovement.toFixed(2)}% (creating discount)`)
  console.log(`   24h Change: ${testParams.marketData.priceChange24h}% (bearish pressure)`)
  console.log(`   RSI Level: ${testParams.marketData.rsi} (oversold territory)`)
  console.log(`   Support Distance: ${((testParams.marketData.support - testParams.currentPosition.currentPrice) / testParams.currentPosition.currentPrice * 100).toFixed(1)}%`)
  console.log(`   Available Balance: $${testParams.accountStatus.availableBalance} (sufficient for DCA)`)
  console.log(`   Current Leverage: ${testParams.accountStatus.leverage}x (room for more)`)

  console.log('\n✅ DCA Testing Complete')
}

// Test edge cases
async function testDCAEdgeCases() {
  console.log('\n🔬 Testing Edge Cases')
  console.log('=' .repeat(30))

  // Test 1: Price moving in favor (should not DCA)
  console.log('\n1️⃣ Testing: Price moving in favor (no DCA expected)')
  const favorableScenario = {
    currentPosition: {
      side: 'long',
      size: 1.0,
      entryPrice: 180.0,
      currentPrice: 185.0, // Price up 2.78%
      unrealizedPnl: 5.0,
      stopLoss: 175.0,
      takeProfit: 190.0
    },
    accountStatus: {
      accountValue: 1000,
      availableBalance: 500,
      leverage: 2.0,
      liquidationPrice: 170.0
    },
    marketData: {
      price: 185.0,
      priceChange24h: 3.5,
      volume: 100000000
    },
    maxLeverageAllowed: 20
  }

  const favorableResult = AIDCAManager.analyzeDCAOpportunity(favorableScenario)
  console.log(`   Result: ${favorableResult.shouldDCA ? 'DCA' : 'NO DCA'} ✅`)
  console.log(`   Reasoning: ${favorableResult.reasoning}`)

  // Test 2: Insufficient balance
  console.log('\n2️⃣ Testing: Insufficient available balance')
  const lowBalanceScenario = {
    currentPosition: {
      side: 'long',
      size: 1.0,
      entryPrice: 185.0,
      currentPrice: 180.0,
      unrealizedPnl: -5.0,
      stopLoss: 175.0,
      takeProfit: 195.0
    },
    accountStatus: {
      accountValue: 100,
      availableBalance: 10, // Very low balance
      leverage: 5.0,
      liquidationPrice: 170.0
    },
    marketData: {
      price: 180.0,
      priceChange24h: -5.0,
      volume: 100000000
    },
    maxLeverageAllowed: 20
  }

  const lowBalanceResult = AIDCAManager.analyzeDCAOpportunity(lowBalanceScenario)
  console.log(`   Result: ${lowBalanceResult.shouldDCA ? 'DCA' : 'NO DCA'} ✅`)
  console.log(`   Reasoning: ${lowBalanceResult.reasoning}`)

  // Test 3: High leverage already (risky to DCA)
  console.log('\n3️⃣ Testing: Already high leverage position')
  const highLeverageScenario = {
    currentPosition: {
      side: 'short',
      size: 5.0,
      entryPrice: 185.0,
      currentPrice: 190.0, // Against position
      unrealizedPnl: -25.0,
      stopLoss: 195.0,
      takeProfit: 175.0
    },
    accountStatus: {
      accountValue: 1000,
      availableBalance: 200,
      leverage: 18.0, // Very high leverage
      liquidationPrice: 195.5
    },
    marketData: {
      price: 190.0,
      priceChange24h: 2.5,
      volume: 100000000,
      rsi: 75 // Overbought (good for shorts)
    },
    maxLeverageAllowed: 20
  }

  const highLeverageResult = AIDCAManager.analyzeDCAOpportunity(highLeverageScenario)
  console.log(`   Result: ${highLeverageResult.shouldDCA ? 'DCA' : 'NO DCA'} ✅`)
  console.log(`   Risk Level: ${highLeverageResult.riskAssessment}`)
  console.log(`   Reasoning: ${highLeverageResult.reasoning}`)
}

// Run all tests
async function runAllTests() {
  try {
    await testDCAAnalysis()
    await testDCAEdgeCases()
    
    console.log('\n🎉 All DCA Tests Completed Successfully!')
    console.log('\n📝 Key Insights:')
    console.log('   • AI DCA system intelligently detects reversal opportunities')
    console.log('   • Respects risk management with leverage and liquidation limits')
    console.log('   • Adjusts stop loss and take profit for improved position')
    console.log('   • Prevents DCA when price moves favorably or risks are too high')
    console.log('   • Considers market conditions, RSI, and support/resistance levels')
    
  } catch (error) {
    console.error('❌ Test failed:', error)
  }
}

runAllTests()
