#!/usr/bin/env node

// Test script to verify position checking prevents analysis
const axios = require('axios');

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

async function testPositionCheck() {
  console.log('🧪 Testing position-aware automation prevention...\n');
  
  try {
    // First, check if there are open positions
    console.log('1. Checking for open 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.marketSymbol} ${pos.side} ${pos.baseAssetAmount}`);
      });
    }
    console.log('');
    
    // Now try to start automation
    console.log('2. Attempting to start automation...');
    const automationResponse = await axios.post(`${BASE_URL}/api/automation/start`, {
      symbol: 'SOLUSD',
      timeframe: '5',
      mode: 'LIVE'
    });
    
    console.log(`✅ Automation start response: ${automationResponse.status}`);
    console.log(`📊 Response: ${JSON.stringify(automationResponse.data, null, 2)}\n`);
    
    // Check automation status
    console.log('3. Checking automation status...');
    const statusResponse = await axios.get(`${BASE_URL}/api/automation/status`);
    console.log(`📊 Status: ${JSON.stringify(statusResponse.data, null, 2)}\n`);
    
    // Try to trigger analysis directly
    console.log('4. Attempting direct analysis...');
    try {
      const analysisResponse = await axios.post(`${BASE_URL}/api/analysis-optimized`, {
        symbol: 'SOLUSD',
        timeframes: ['5', '15'],
        layouts: ['ai', 'diy'],
        analyze: true
      });
      
      console.log(`✅ Analysis response: ${analysisResponse.status}`);
      console.log(`📊 Should be blocked if positions exist!\n`);
    } catch (error) {
      if (error.response?.status === 400 && error.response?.data?.message?.includes('position')) {
        console.log(`✅ Analysis correctly blocked: ${error.response.data.message}\n`);
      } else {
        console.log(`❌ Unexpected error: ${error.message}\n`);
      }
    }
    
  } catch (error) {
    console.error('❌ Test failed:', error.response?.data || error.message);
  }
}

testPositionCheck();
