#!/usr/bin/env node

/**
 * Show Last AI Decision Script
 * Forces the automation to analyze current market conditions and displays the AI decision
 */

async function showLastAIDecision() {
  try {
    console.log('🔍 Checking for AI automation decisions...\n');
    
    // 1. Check current automation status
    console.log('📊 AUTOMATION STATUS:');
    const statusResponse = await fetch('http://localhost:3000/api/automation/status');
    const statusData = await statusResponse.json();
    console.log(`   Running: ${statusData.isRunning ? '✅ YES' : '❌ NO'}`);
    console.log(`   Strategy: ${statusData.strategy || 'Not set'}`);
    console.log(`   Mode: ${statusData.mode || 'Not set'}`);
    console.log(`   Timeframes: ${statusData.selectedTimeframes?.join(', ') || 'Not set'}`);
    
    // 2. Check if there's a recent decision
    console.log('\n🧠 LAST AI DECISION:');
    if (statusData.lastDecision) {
      const decision = statusData.lastDecision;
      console.log(`   📈 Recommendation: ${decision.recommendation || 'None'}`);
      console.log(`   🎯 Confidence: ${decision.confidence || 0}%`);
      console.log(`   💰 Entry Price: $${decision.executionDetails?.currentPrice || 'N/A'}`);
      console.log(`   🛑 Stop Loss: $${decision.executionDetails?.stopLoss || 'N/A'}`);
      console.log(`   🎯 Take Profit: $${decision.executionDetails?.takeProfit || 'N/A'}`);
      console.log(`   📅 Timestamp: ${decision.timestamp || 'N/A'}`);
      console.log(`   📝 AI Reasoning:`);
      console.log(`      ${decision.reasoning || 'No reasoning provided'}`);
    } else {
      console.log('   ❌ No recent AI decision found');
    }
    
    // 3. Check current position status
    console.log('\n💼 CURRENT POSITION:');
    const posResponse = await fetch('http://localhost:3000/api/drift/positions');
    const posData = await posResponse.json();
    
    if (posData.positions && posData.positions.length > 0) {
      const position = posData.positions[0];
      console.log(`   📊 Position: ${position.side} ${position.size} SOL`);
      console.log(`   💵 Entry Price: $${position.entryPrice?.toFixed(4) || 'N/A'}`);
      console.log(`   📈 Current Price: $${position.markPrice?.toFixed(4) || 'N/A'}`);
      
      // Calculate P&L
      if (position.entryPrice && position.markPrice) {
        const pnl = position.side.toLowerCase() === 'long' ? 
          (position.markPrice - position.entryPrice) * position.size :
          (position.entryPrice - position.markPrice) * position.size;
        console.log(`   💰 Current P&L: $${pnl.toFixed(2)} ${pnl >= 0 ? '✅' : '❌'}`);
      }
    } else {
      console.log('   📭 No active positions');
    }
    
    // 4. Check recent AI analysis activity
    console.log('\n📈 RECENT AI ANALYSIS:');
    try {
      const analysisResponse = await fetch('http://localhost:3000/api/automation/analysis-details');
      const analysisData = await analysisResponse.json();
      
      if (analysisData.success && analysisData.data) {
        console.log(`   🔍 Analysis Status: ${analysisData.data.analysis?.decision || 'No decision'}`);
        console.log(`   🎯 Confidence: ${analysisData.data.analysis?.confidence || 0}%`);
        console.log(`   📊 Market Sentiment: ${analysisData.data.analysis?.sentiment || 'Unknown'}`);
        console.log(`   📅 Last Analysis: ${analysisData.data.session?.lastAnalysisAt || 'Unknown'}`);
      }
    } catch (analysisError) {
      console.log('   ❌ Could not fetch analysis details');
    }
    
    // 5. Force new analysis if automation is running but no recent decision
    if (statusData.isRunning && !statusData.lastDecision) {
      console.log('\n🔄 AUTOMATION IS RUNNING BUT NO RECENT DECISIONS...');
      console.log('   💡 The AI is likely in analysis mode or waiting for optimal entry conditions');
      console.log('   📊 Check the automation-v2 page for real-time analysis updates');
      console.log('   🕐 Next analysis cycle should complete within 2 minutes');
    }
    
    console.log('\n✅ AI Decision Check Complete!');
    console.log('📱 View live updates at: http://localhost:9001/automation-v2');
    
  } catch (error) {
    console.error('❌ Error checking AI decision:', error.message);
  }
}

showLastAIDecision();
