import priceMonitorService from './lib/price-monitor.js';
import { PriceFetcher } from './lib/price-fetcher.js';

async function testPriceMonitorBasic() {
  console.log('🧪 Testing Basic Price Monitor Functionality...\n');

  try {
    // Test 1: Price fetcher integration
    console.log('1️⃣ Testing PriceFetcher integration...');
    const priceFetcher = new PriceFetcher();
    const solPrice = await priceFetcher.getPrice('SOL');
    console.log(`SOL Price: $${solPrice}`);
    console.log('✅ PriceFetcher working\n');

    // Test 2: Price monitor initialization
    console.log('2️⃣ Testing price monitor initialization...');
    const initialStatus = priceMonitorService.isMonitoring();
    console.log(`Initial status: ${initialStatus ? 'Active' : 'Inactive'}`);
    console.log('✅ Price monitor initialized\n');

    // Test 3: Event listener setup
    console.log('3️⃣ Testing event listener setup...');
    let eventReceived = false;
    
    priceMonitorService.on('test_event', (data) => {
      console.log('Event received:', data);
      eventReceived = true;
    });
    
    priceMonitorService.emit('test_event', { test: 'data' });
    
    // Wait for event
    await new Promise(resolve => setTimeout(resolve, 100));
    console.log(`Event test: ${eventReceived ? '✅ Success' : '❌ Failed'}\n`);

    // Test 4: Start monitoring
    console.log('4️⃣ Testing start monitoring...');
    await priceMonitorService.startMonitoring();
    const monitoringStatus = priceMonitorService.isMonitoring();
    console.log(`Monitoring status: ${monitoringStatus ? '✅ Active' : '❌ Inactive'}\n`);

    // Test 5: Get monitoring data
    console.log('5️⃣ Testing get monitoring data...');
    const monitoringData = await priceMonitorService.getMonitoringData();
    console.log('Monitoring data structure:', {
      hasTradesArray: Array.isArray(monitoringData.trades),
      hasAlertsArray: Array.isArray(monitoringData.alerts),
      hasPricesObject: typeof monitoringData.prices === 'object',
      hasLastUpdated: !!monitoringData.lastUpdated,
      monitoringActive: monitoringData.monitoringActive
    });
    console.log('✅ Monitoring data structure valid\n');

    // Test 6: Price update simulation
    console.log('6️⃣ Testing price update simulation...');
    let priceUpdateReceived = false;
    
    priceMonitorService.on('price_update', (data) => {
      console.log('Price update received:', data.symbol, data.price);
      priceUpdateReceived = true;
    });
    
    // Manually trigger a price update for testing
    priceMonitorService.emit('price_update', { 
      symbol: 'SOLUSD', 
      price: 189.50,
      timestamp: new Date().toISOString()
    });
    
    await new Promise(resolve => setTimeout(resolve, 100));
    console.log(`Price update test: ${priceUpdateReceived ? '✅ Success' : '❌ Failed'}\n`);

    // Test 7: Stop monitoring
    console.log('7️⃣ Testing stop monitoring...');
    await priceMonitorService.stopMonitoring();
    const stoppedStatus = priceMonitorService.isMonitoring();
    console.log(`Stopped status: ${stoppedStatus ? '❌ Still active' : '✅ Stopped'}\n`);

    console.log('🎉 All basic price monitor tests completed successfully!');

    return {
      priceFetcher: !!solPrice,
      initialization: true,
      eventListeners: eventReceived,
      startMonitoring: monitoringStatus,
      monitoringData: !!monitoringData,
      priceUpdates: priceUpdateReceived,
      stopMonitoring: !stoppedStatus
    };

  } catch (error) {
    console.error('❌ Basic test failed:', error);
    console.error('Stack trace:', error.stack);
    throw error;
  }
}

// Run the test
if (import.meta.url === `file://${process.argv[1]}`) {
  testPriceMonitorBasic()
    .then((results) => {
      console.log('\n📊 Test Results Summary:');
      Object.entries(results).forEach(([test, passed]) => {
        console.log(`  ${test}: ${passed ? '✅' : '❌'}`);
      });
      
      const allPassed = Object.values(results).every(result => result);
      console.log(`\nOverall: ${allPassed ? '✅ All tests passed' : '❌ Some tests failed'}`);
      process.exit(allPassed ? 0 : 1);
    })
    .catch((error) => {
      console.error('\n❌ Test suite failed:', error.message);
      process.exit(1);
    });
}

export { testPriceMonitorBasic };
