#!/usr/bin/env node

/**
 * Safe automation starter - checks position status before starting
 */

const axios = require('axios');

const BASE_URL = 'http://localhost:9001';

async function startAutomationSafely() {
  console.log('🚀 Starting Position-Aware Automation Safely...\n');
  
  try {
    // 1. Check current positions first
    console.log('1. Checking current positions...');
    const positionsResponse = await axios.get(`${BASE_URL}/api/drift/positions`);
    const positions = positionsResponse.data.positions || [];
    
    console.log(`📊 Found ${positions.length} open position(s)`);
    if (positions.length > 0) {
      positions.forEach((pos, idx) => {
        console.log(`   ${idx + 1}. ${pos.symbol} ${pos.side.toUpperCase()} ${pos.size} SOL`);
        console.log(`      Entry: $${pos.entryPrice.toFixed(4)}, Current: $${pos.markPrice.toFixed(4)}`);
        console.log(`      P&L: ${pos.unrealizedPnl >= 0 ? '+' : ''}$${pos.unrealizedPnl.toFixed(2)}`);
      });
    }
    console.log('');
    
    // 2. Start automation with position-aware configuration
    console.log('2. Starting position-aware automation...');
    const automationConfig = {
      symbol: 'SOLUSD',
      mode: 'LIVE',  // Set to LIVE for real trading
      selectedTimeframes: ['5', '15'],  // Scalping timeframes
      enableTrading: true,  // Enable real trades
      tradingAmount: 100,   // Position size in USD
      maxLeverage: 10,      // Maximum leverage
      riskPercentage: 2,    // 2% risk per trade
      maxDailyTrades: 5,    // Maximum 5 trades per day
      stopLoss: 1.0,        // 1% stop loss
      takeProfit: 2.0,      // 2% take profit
      dexProvider: 'DRIFT'
    };
    
    const automationResponse = await axios.post(`${BASE_URL}/api/automation/start`, automationConfig);
    
    if (automationResponse.data.success) {
      console.log('✅ Automation started successfully!');
      console.log(`📊 Mode: ${automationConfig.mode}`);
      console.log(`💰 Trading: ${automationConfig.enableTrading ? 'ENABLED' : 'SIMULATION ONLY'}`);
      console.log(`🎯 Symbol: ${automationConfig.symbol}`);
      console.log(`⏱️ Timeframes: ${automationConfig.selectedTimeframes.join(', ')}`);
      
      if (positions.length > 0) {
        console.log('\n🎯 INTELLIGENT BEHAVIOR:');
        console.log('   ✅ Will monitor existing position for stop loss proximity');
        console.log('   ✅ Will switch to DCA/doubling down if price approaches SL');
        console.log('   ✅ Will scan for new opportunities only after position closes');
      } else {
        console.log('\n🎯 SCANNING MODE:');
        console.log('   ✅ Will scan for new entry opportunities');
        console.log('   ✅ Will execute trades based on AI analysis');
      }
      
    } else {
      console.error('❌ Failed to start automation:', automationResponse.data.error);
    }
    
    // 3. Check final status
    console.log('\n3. Checking automation status...');
    const statusResponse = await axios.get(`${BASE_URL}/api/automation/status`);
    console.log(`📊 Status: ${JSON.stringify(statusResponse.data, null, 2)}`);
    
  } catch (error) {
    console.error('❌ Error starting automation:', error.response?.data || error.message);
  }
}

// Run the automation starter
startAutomationSafely()
  .then(() => {
    console.log('\n✅ Automation startup completed');
  })
  .catch((error) => {
    console.error('❌ Startup failed:', error);
  });
