const https = require('https');
const http = require('http');

function httpsGet(url) {
  return new Promise((resolve, reject) => {
    https.get(url, (res) => {
      let data = '';
      res.on('data', (chunk) => data += chunk);
      res.on('end', () => {
        try {
          resolve(JSON.parse(data));
        } catch (error) {
          reject(error);
        }
      });
    }).on('error', reject);
  });
}

function httpGet(url) {
  return new Promise((resolve, reject) => {
    http.get(url, (res) => {
      let data = '';
      res.on('data', (chunk) => data += chunk);
      res.on('end', () => {
        try {
          resolve(JSON.parse(data));
        } catch (error) {
          reject(error);
        }
      });
    }).on('error', reject);
  });
}

async function testPriceSource() {
  console.log('🧪 Testing price source hierarchy...\n');
  
  try {
    // Test CoinGecko directly
    console.log('1. Testing CoinGecko API directly...');
    const cgData = await httpsGet('https://api.coingecko.com/api/v3/simple/price?ids=solana&vs_currencies=usd');
    const cgPrice = cgData?.solana?.usd;
    console.log('✅ CoinGecko SOLUSD price:', cgPrice);
  } catch (error) {
    console.log('❌ CoinGecko error:', error.message);
  }
  
  try {
    // Test CoinCap directly  
    console.log('\n2. Testing CoinCap API directly...');
    const ccData = await httpsGet('https://api.coincap.io/v2/assets/solana');
    const ccPrice = parseFloat(ccData?.data?.priceUsd);
    console.log('✅ CoinCap SOLUSD price:', ccPrice);
  } catch (error) {
    console.log('❌ CoinCap error:', error.message);
  }
  
  try {
    // Test Binance directly
    console.log('\n3. Testing Binance API directly...');
    const binanceData = await httpsGet('https://api.binance.com/api/v3/ticker/price?symbol=SOLUSDT');
    const binancePrice = parseFloat(binanceData?.price);
    console.log('✅ Binance SOLUSD price:', binancePrice);
  } catch (error) {
    console.log('❌ Binance error:', error.message);
  }
  
  try {
    // Test our price monitor
    console.log('\n4. Testing our price monitor...');
    const pmData = await httpGet('http://localhost:3000/api/price-monitor');
    const pmPrice = pmData?.data?.prices?.SOLUSD;
    console.log('✅ Price Monitor SOLUSD price:', pmPrice);
    console.log('📊 Price Monitor source: Likely CoinGecko (primary) or CoinCap (fallback)');
  } catch (error) {
    console.log('❌ Price Monitor error:', error.message);
  }
}

testPriceSource().catch(console.error);
