#!/usr/bin/env node

/**
 * Stable Risk Monitor
 * 
 * A lightweight version that monitors positions without complex fetch operations
 */

const HttpUtil = require('./http-util');

class StableRiskMonitor {
  constructor() {
    this.isActive = false;
    this.lastCheck = null;
  }

  async log(message) {
    const timestamp = new Date().toISOString();
    console.log(`[${timestamp}] 🤖 AI Monitor: ${message}`);
  }

  async checkPosition() {
    try {
      const data = await HttpUtil.get('http://localhost:9001/api/automation/position-monitor');
      
      if (data.success && data.monitor) {
        return this.analyzeRisk(data.monitor);
      }
      
      return { status: 'NO_DATA', message: 'No position data available' };
    } catch (error) {
      return { status: 'ERROR', message: `Monitor error: ${error.message}` };
    }
  }

  analyzeRisk(monitor) {
    if (!monitor.hasPosition) {
      return { 
        status: 'NO_POSITION', 
        message: '📊 No positions - AI scanning for opportunities',
        action: 'OPPORTUNITY_SCAN'
      };
    }

    const { position, stopLossProximity, riskLevel } = monitor;
    const distance = parseFloat(stopLossProximity.distancePercent);
    
    let analysis = {
      status: 'MONITORING',
      position: `${position.symbol} ${position.side.toUpperCase()} ${position.size}`,
      pnl: position.unrealizedPnl,
      distance: `${distance}%`,
      riskLevel: riskLevel
    };

    if (distance < 1.0) {
      analysis.action = '🚨 AI: Emergency protocols - Preparing exit strategies';
      analysis.urgency = 'CRITICAL';
    } else if (distance < 2.0) {
      analysis.action = '⚠️ AI: High risk analysis - Reviewing position parameters';
      analysis.urgency = 'HIGH';
    } else if (distance < 5.0) {
      analysis.action = '🟡 AI: Enhanced monitoring - Preparing contingencies';
      analysis.urgency = 'MEDIUM';
    } else {
      analysis.action = '✅ AI: Position secure - Scanning for opportunities';
      analysis.urgency = 'LOW';
    }

    return analysis;
  }

  async startMonitoring() {
    await this.log('🏖️ STABLE BEACH MODE: Autonomous monitoring started');
    this.isActive = true;

    const monitor = async () => {
      if (!this.isActive) return;

      try {
        const analysis = await this.checkPosition();
        
        if (analysis.status === 'MONITORING') {
          await this.log(`${analysis.position} | P&L: $${analysis.pnl?.toFixed(2)} | SL: ${analysis.distance} | ${analysis.action}`);
        } else {
          await this.log(analysis.message);
        }

        this.lastCheck = new Date();
      } catch (error) {
        await this.log(`Monitor cycle error: ${error.message}`);
      }

      // Schedule next check
      if (this.isActive) {
        setTimeout(monitor, 60000); // Check every minute
      }
    };

    // Start monitoring
    monitor();
  }

  stop() {
    this.isActive = false;
    this.log('🛑 Beach mode monitoring stopped');
  }
}

// Export for use in other modules
module.exports = StableRiskMonitor;

// Direct execution
if (require.main === module) {
  const monitor = new StableRiskMonitor();
  monitor.startMonitoring();
  
  console.log('🏖️ Stable Risk Monitor started');
  console.log('📊 Monitoring your positions autonomously');
  console.log('🚨 Press Ctrl+C to stop');
  
  process.on('SIGINT', () => {
    monitor.stop();
    process.exit(0);
  });
}
