#!/usr/bin/env node

/**
 * DEMONSTRATE COMPLETE TRADE OUTCOME TRACKING
 * Shows how the AI learns from trade wins/losses on Drift Protocol
 */

async function demonstrateOutcomeTracking() {
  console.log('🎯 DRIFT PROTOCOL OUTCOME TRACKING DEMONSTRATION')
  console.log('='.repeat(70))
  
  console.log(`
📊 HOW THE AI LEARNS WIN/LOSS FROM REAL TRADES:

1. 🚀 TRADE EXECUTION (Already Working):
   ✅ Place order on Drift Protocol 
   ✅ Create learning record in database
   ✅ Store entry price, stop loss, take profit
   ✅ Record transaction IDs

2. 🔄 OUTCOME MONITORING (Need to Start):
   🔍 Monitor Drift positions every 30 seconds
   📊 Check if position is still open or closed
   💰 Determine if closed via stop loss or take profit
   📈 Calculate actual profit/loss percentage

3. 📚 LEARNING UPDATE (Automatic):
   ✅ Update trade record with WIN/LOSS/BREAKEVEN
   🧠 Link outcome back to AI analysis
   📊 Calculate prediction accuracy
   🚀 Improve AI for next trade

`)

  console.log('🔧 CURRENT STATUS CHECK:')
  
  try {
    // Check current monitoring status
    const statusResponse = await fetch('http://localhost:3000/api/drift/feedback')
    const status = await statusResponse.json()
    
    console.log('📊 Feedback Loop Status:', status.monitoring.status)
    
    if (status.monitoring.status === 'STOPPED') {
      console.log('\n🚀 Starting outcome monitoring...')
      
      const startResponse = await fetch('http://localhost:3000/api/drift/feedback', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ action: 'start_monitoring' })
      })
      
      const startResult = await startResponse.json()
      
      if (startResult.success) {
        console.log('✅ Monitoring started successfully!')
        console.log('🔄 System now checking trade outcomes every 30 seconds')
      } else {
        console.log('❌ Failed to start monitoring:', startResult.details)
        console.log('💡 This is expected if RPC has limitations')
      }
    } else {
      console.log('✅ Monitoring already active')
    }
    
  } catch (error) {
    console.error('❌ Status check failed:', error.message)
  }
  
  console.log('\n📋 CHECKING RECENT TRADES FOR OUTCOME EXAMPLES:')
  
  try {
    const { PrismaClient } = await import('@prisma/client')
    const prisma = new PrismaClient()
    
    // Get recent real Drift trades
    const recentTrades = await prisma.trade.findMany({
      where: {
        userId: 'default-user',
        tradingMode: 'REAL',
        driftTxId: { not: null }
      },
      orderBy: { createdAt: 'desc' },
      take: 5
    })
    
    console.log(`\n🔍 Found ${recentTrades.length} recent real Drift trades:`)
    
    recentTrades.forEach((trade, index) => {
      const outcomeEmoji = trade.outcome === 'WIN' ? '🟢' : 
                          trade.outcome === 'LOSS' ? '🔴' : 
                          trade.outcome === 'BREAKEVEN' ? '🟡' : '⏳'
      
      console.log(`   ${index + 1}. ${outcomeEmoji} ${trade.symbol} ${trade.side.toUpperCase()} - ${trade.outcome || 'PENDING'}`)
      console.log(`      Entry: $${trade.entryPrice || trade.price}`)
      console.log(`      Stop: $${trade.stopLoss} | Target: $${trade.takeProfit}`)
      console.log(`      P&L: ${trade.pnlPercent ? trade.pnlPercent.toFixed(2) + '%' : 'Pending'}`)
      console.log(`      Status: ${trade.status}`)
      console.log(`      Created: ${trade.createdAt.toISOString().slice(0, 19).replace('T', ' ')}`)
      console.log('')
    })
    
    // Show outcome statistics
    const completedTrades = recentTrades.filter(t => t.outcome)
    if (completedTrades.length > 0) {
      const wins = completedTrades.filter(t => t.outcome === 'WIN').length
      const winRate = (wins / completedTrades.length * 100).toFixed(1)
      const avgPnL = completedTrades.reduce((sum, t) => sum + (t.pnlPercent || 0), 0) / completedTrades.length
      
      console.log('📊 LEARNING STATISTICS:')
      console.log(`   Total Completed: ${completedTrades.length}`)
      console.log(`   Win Rate: ${winRate}%`)
      console.log(`   Average P&L: ${avgPnL.toFixed(2)}%`)
    } else {
      console.log('⏳ No completed trades yet - outcomes still being monitored')
    }
    
    await prisma.$disconnect()
    
  } catch (error) {
    console.error('❌ Database check failed:', error.message)
  }
}

async function demonstrateOutcomeDetection() {
  console.log('\n🔍 HOW OUTCOME DETECTION WORKS:')
  console.log('='.repeat(50))
  
  console.log(`
🎯 DRIFT POSITION MONITORING:

1. Every 30 seconds, system checks Drift account
2. Compares current positions with open trades  
3. Detects when position is closed or reduced

📊 OUTCOME DETECTION LOGIC:

For a BUY trade:
• If position closed above stop loss → Check if TP hit or manual close
• If position closed at/near stop loss → Outcome = LOSS 
• If position closed at/near take profit → Outcome = WIN
• Calculate exact P&L percentage from entry to exit

For a SELL trade:  
• Same logic but inverted price movements
• Stop loss above entry, take profit below entry

💰 P&L CALCULATION:
• Entry Price: $183.24 (from trade record)
• Exit Price: $185.99 (detected when position closes)  
• P&L = ((185.99 - 183.24) / 183.24) * 100 = +1.50%
• Outcome = WIN (profitable trade)

🧠 AI LEARNING UPDATE:
• Trade record updated: outcome = 'WIN', pnlPercent = 1.50
• AI analysis linked: predicted outcome vs actual outcome
• Accuracy score calculated and stored
• Pattern recognition improved for future trades
`)

  console.log('🚀 TRIGGER MANUAL OUTCOME CHECK:')
  
  try {
    const checkResponse = await fetch('http://localhost:3000/api/drift/feedback', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ action: 'check_trades' })
    })
    
    const checkResult = await checkResponse.json()
    
    if (checkResult.success) {
      console.log('✅ Manual outcome check completed')
      console.log('🔄 Any closed positions should now be detected')
    } else {
      console.log('❌ Manual check failed:', checkResult.error)
    }
    
  } catch (error) {
    console.error('❌ Manual check failed:', error.message)
  }
}

async function showLearningInsights() {
  console.log('\n🧠 AI LEARNING INSIGHTS:')
  console.log('='.repeat(40))
  
  try {
    const insightsResponse = await fetch('http://localhost:3000/api/drift/feedback', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ action: 'get_insights' })
    })
    
    const insights = await insightsResponse.json()
    
    if (insights.success) {
      console.log('📊 Current Performance:')
      console.log(`   Total Trades: ${insights.insights.recentPerformance.totalTrades}`)
      console.log(`   Win Rate: ${insights.insights.recentPerformance.winRate}`)
      console.log(`   Avg P&L: ${insights.insights.recentPerformance.avgPnL}`)
      console.log(`   Time Range: ${insights.insights.recentPerformance.timeRange}`)
      console.log(`   Feedback Status: ${insights.insights.feedbackLoopStatus}`)
      
      if (insights.insights.latestInsights) {
        console.log('\n🎯 Latest Learning Insights:')
        console.log(JSON.stringify(insights.insights.latestInsights, null, 2))
      } else {
        console.log('\n⏳ No comprehensive insights yet - need more completed trades')
      }
    }
    
  } catch (error) {
    console.error('❌ Insights check failed:', error.message)
  }
}

if (require.main === module) {
  demonstrateOutcomeTracking()
    .then(() => demonstrateOutcomeDetection())
    .then(() => showLearningInsights())
    .then(() => {
      console.log('\n🎉 COMPLETE LEARNING CYCLE DEMONSTRATED!')
      console.log('\n💡 NEXT STEPS:')
      console.log('1. Keep monitoring running for automatic outcome detection')
      console.log('2. Place more trades to build learning database') 
      console.log('3. AI will improve accuracy based on real results')
      console.log('4. Check insights regularly to see learning progress')
    })
}
