/**
 * Example usage of the SPORE API Client with Discovery
 */

const SporeApiClient = require('./index');

async function main() {
  console.log('🚀 SPORE API Client Example with Discovery');
  console.log('==========================================\n');

  // First, check if we can discover nodes through the backend
  console.log('1. Checking for discovered nodes...');
  try {
    const response = await fetch('http://localhost:3001/api/discovery/nodes');
    const discoveryData = await response.json();
    
    if (discoveryData.totalNodes > 0) {
      console.log(`✅ Found ${discoveryData.totalNodes} discovered node(s)`);
      console.log(`Primary node: ${discoveryData.primaryNode}`);
      
      // Use the discovered primary node
      const client = new SporeApiClient(`http://${discoveryData.primaryNode}`);
      await runExamples(client);
    } else {
      console.log('❌ No nodes discovered yet.');
      console.log('💡 Start the backend server and send CLUSTER_HEARTBEAT messages');
      console.log('💡 Use: npm run test-heartbeat broadcast');
      return;
    }
  } catch (error) {
    console.log('❌ Could not connect to backend discovery service');
    console.log('💡 Make sure the backend server is running on port 3001');
    console.log('💡 Use: npm start');
    return;
  }
}

async function runExamples(client) {
  console.log('\n2. Getting system status...');
  try {
    const systemStatus = await client.getSystemStatus();
    console.log('✅ System Status:', JSON.stringify(systemStatus, null, 2));
  } catch (error) {
    console.log('❌ Failed to get system status:', error.message);
  }
  console.log('');

  console.log('3. Getting task status...');
  try {
    const taskStatus = await client.getTaskStatus();
    console.log('✅ Task Status:', JSON.stringify(taskStatus, null, 2));
  } catch (error) {
    console.log('❌ Failed to get task status:', error.message);
  }
  console.log('');

  console.log('4. Getting cluster discovery...');
  try {
    const discovery = await client.getClusterDiscovery();
    console.log('✅ Cluster Discovery:', JSON.stringify(discovery, null, 2));
  } catch (error) {
    console.log('❌ Failed to get cluster discovery:', error.message);
  }
  console.log('');

  console.log('🎉 API calls completed!');
}

// Alternative: Direct connection to a specific IP (for testing)
async function directConnection(ip) {
  console.log(`\n🔌 Direct connection to ${ip}...`);
  const client = new SporeApiClient(`http://${ip}`);
  await runExamples(client);
}

// Run the example if this file is executed directly
if (require.main === module) {
  const args = process.argv.slice(2);
  
  if (args.length > 0) {
    // Allow direct connection for testing: node example.js 192.168.1.100
    directConnection(args[0]).catch(console.error);
  } else {
    // Use discovery system
    main().catch(console.error);
  }
}

module.exports = { main, directConnection }; 