#!/usr/bin/env node

/**
 * Real-time Position & Automation Monitor
 * 
 * Enhanced with:
 * - Real-time P&L tracking
 * - Stop loss alerts  
 * - Analysis progress indicators
 * - Performance metrics
 */

const baseUrl = 'http://localhost:9001';
let startTime = Date.now();
let lastPnl = null;
let alertSound = false;

async function fetchData(endpoint) {
  try {
    const response = await fetch(`${baseUrl}${endpoint}`);
    return await response.json();
  } catch (error) {
    return { error: error.message };
  }
}

function getRunningTime() {
  const elapsed = Date.now() - startTime;
  const minutes = Math.floor(elapsed / 60000);
  const seconds = Math.floor((elapsed % 60000) / 1000);
  return `${minutes}m ${seconds}s`;
}

function getPnlTrend(currentPnl) {
  if (lastPnl === null) {
    lastPnl = currentPnl;
    return '';
  }
  
  const diff = currentPnl - lastPnl;
  lastPnl = currentPnl;
  
  if (Math.abs(diff) < 0.01) return ' ➡️';
  return diff > 0 ? ' 📈' : ' 📉';
}

async function monitor() {
  console.clear();
  console.log('🔍 TRADING BOT POSITION MONITOR');
  console.log('=' .repeat(60));
  console.log(`⏰ ${new Date().toLocaleString()} | Running: ${getRunningTime()}\n`);

  // Get position status
  const positionData = await fetchData('/api/automation/position-monitor');
  
  if (positionData.success && positionData.monitor.hasPosition) {
    const pos = positionData.monitor.position;
    const sl = positionData.monitor.stopLossProximity;
    const trend = getPnlTrend(pos.unrealizedPnl);
    
    console.log('📊 ACTIVE POSITION:');
    console.log(`   ${pos.symbol} | ${pos.side.toUpperCase()} | ${pos.size} SOL`);
    console.log(`   Entry: $${pos.entryPrice.toFixed(4)} → Current: $${pos.currentPrice.toFixed(4)}`);
    console.log(`   P&L: ${pos.unrealizedPnl >= 0 ? '🟢 +' : '🔴 '}$${pos.unrealizedPnl.toFixed(2)}${trend}`);
    console.log(`   Value: $${pos.notionalValue.toFixed(2)}`);
    console.log('');
    
    // Enhanced stop loss display
    const distanceNum = parseFloat(sl.distancePercent);
    let statusIcon = '✅';
    let statusText = 'SAFE';
    
    if (distanceNum <= 2) {
      statusIcon = '🚨';
      statusText = 'DANGER - VERY CLOSE';
    } else if (distanceNum <= 5) {
      statusIcon = '⚠️';
      statusText = 'WARNING - APPROACHING';
    } else if (distanceNum <= 10) {
      statusIcon = '🟡';
      statusText = 'CAUTION - MONITOR';
    }
    
    console.log('🛡️ STOP LOSS PROTECTION:');
    console.log(`   Stop Loss: $${sl.stopLossPrice.toFixed(4)} (${sl.distancePercent}% away)`);
    console.log(`   Status: ${statusIcon} ${statusText}`);
    console.log(`   Risk Level: ${positionData.monitor.riskLevel}`);
    
    if (sl.isNear) {
      console.log('\n🚨 ALERT: PRICE NEAR STOP LOSS! 🚨');
    }
    console.log('');
    
  } else if (positionData.success) {
    console.log('📊 NO OPEN POSITIONS');
    console.log('   Status: Scanning for opportunities...');
    console.log('');
  } else {
    console.log('❌ CONNECTION ERROR');
    console.log('   Check if trading bot is running on port 9001');
    console.log('');
  }

  // Enhanced automation status
  const autoStatus = await fetchData('/api/automation/status');
  
  if (autoStatus.isActive) {
    console.log('🤖 AUTOMATION ENGINE:');
    console.log(`   Status: ✅ ACTIVE (${autoStatus.mode})`);
    console.log(`   Strategy: ${autoStatus.automationType || 'Scalping'}`);
    console.log(`   Markets: ${autoStatus.symbol} [${autoStatus.timeframes?.join(', ') || 'N/A'}]`);
    console.log(`   Performance: ${autoStatus.totalCycles} cycles, ${autoStatus.totalTrades} trades`);
    
    if (autoStatus.lastActivity) {
      const lastSeen = new Date(autoStatus.lastActivity);
      const timeSince = Math.floor((Date.now() - lastSeen.getTime()) / 1000);
      const activityStatus = timeSince < 180 ? '🟢 Active' : '🟡 Quiet';
      console.log(`   Last Activity: ${activityStatus} (${timeSince}s ago)`);
    }
    
    // Error monitoring
    if (autoStatus.consecutiveErrors > 0) {
      const errorLevel = autoStatus.consecutiveErrors >= 2 ? '🔴' : '🟡';
      console.log(`   ${errorLevel} Errors: ${autoStatus.consecutiveErrors}/3 consecutive`);
    }
    
    // Analysis status (if running for long time)
    const timeSince = autoStatus.lastActivity ? 
      Math.floor((Date.now() - new Date(autoStatus.lastActivity).getTime()) / 1000) : 0;
    
    if (timeSince > 60 && timeSince < 300) {
      console.log(`   🔄 Likely analyzing... (${timeSince}s since last update)`);
    }
    
  } else {
    console.log('🤖 AUTOMATION ENGINE: ❌ OFFLINE');
    console.log(`   Status: ${autoStatus.detailedStatus || 'Stopped'}`);
    console.log(`   Action: ${autoStatus.nextAction || 'Start automation to begin'}`);
  }
  
  console.log('');
  console.log('� CONTROLS:');
  console.log('   • Ctrl+C: Stop monitor  • Updates every 8 seconds');
  console.log('   • Real-time P&L tracking • Stop loss proximity alerts');
  console.log('-'.repeat(60));
}

// Graceful shutdown
process.on('SIGINT', () => {
  console.clear();
  console.log('🔍 TRADING BOT MONITOR - SESSION COMPLETE');
  console.log('=' .repeat(60));
  console.log('');
  console.log('📊 Session Summary:');
  console.log(`   Duration: ${getRunningTime()}`);
  console.log(`   Last P&L: ${lastPnl ? `$${lastPnl.toFixed(2)}` : 'No position tracked'}`);
  console.log('');
  console.log('💡 Quick Commands:');
  console.log('   ./monitor-position.js    - Start monitor again');
  console.log('   curl localhost:9001/api/automation/status | jq .    - Quick status');
  console.log('   docker logs trading_bot -f    - View live logs');
  console.log('');
  console.log('� Thank you for monitoring responsibly!');
  console.log('');
  process.exit(0);
});

// Start monitoring
console.log('🚀 Initializing position monitor...');
monitor();
const monitorInterval = setInterval(monitor, 8000); // Update every 8 seconds
