// Deep WAHA debugging to find the real issue
async function deepWahaDebug() {
  console.log('🔍 DEEP WAHA DEBUGGING - FINDING THE REAL ISSUE');
  console.log('='.repeat(70));
  
  try {
    // 1. Check WAHA container status
    console.log('1️⃣ Checking WAHA container status...');
    try {
      const { execSync } = require('child_process');
      const dockerStatus = execSync('docker ps | grep waha', { encoding: 'utf8' });
      console.log('✅ WAHA container is running:');
      console.log('   ' + dockerStatus.trim());
    } catch (error) {
      console.log('❌ WAHA container check failed:', error.message);
    }
    
    // 2. Test basic WAHA connectivity
    console.log('\n2️⃣ Testing basic WAHA connectivity...');
    try {
      const response = await fetch('http://localhost:3005/', {
        timeout: 5000
      });
      console.log(`✅ WAHA HTTP: ${response.status} ${response.statusText}`);
    } catch (error) {
      console.log('❌ WAHA HTTP failed:', error.message);
      console.log('   Try: docker restart waha');
      return;
    }
    
    // 3. Get detailed session info
    console.log('\n3️⃣ Getting detailed session information...');
    const sessionResponse = await fetch('http://localhost:3005/api/sessions', {
      headers: { 'X-Api-Key': '992659f827564646ba3ab95ead50adc9' }
    });
    
    if (sessionResponse.ok) {
      const sessions = await sessionResponse.json();
      console.log('📱 Session details:');
      console.log(JSON.stringify(sessions, null, 2));
      
      const defaultSession = sessions.find(s => s.name === 'default');
      
      if (!defaultSession) {
        console.log('❌ PROBLEM: No default session exists!');
        console.log('🔧 Creating session...');
        
        // Create session
        const createResponse = await fetch('http://localhost:3005/api/sessions', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'X-Api-Key': '992659f827564646ba3ab95ead50adc9'
          },
          body: JSON.stringify({
            name: 'default',
            config: {
              webhooks: [{
                url: 'http://host.docker.internal:3000/api/webhooks/waha',
                events: ['message', 'message.ack', 'session.status']
              }]
            }
          })
        });
        
        if (createResponse.ok) {
          console.log('✅ Session created successfully');
        } else {
          console.log('❌ Session creation failed:', await createResponse.text());
        }
        return;
      }
      
      // 4. Check if session needs QR code
      if (defaultSession.status === 'SCAN_QR_CODE') {
        console.log('\n4️⃣ Session needs QR code scan...');
        
        const qrResponse = await fetch('http://localhost:3005/api/default/auth/qr', {
          headers: { 'X-Api-Key': '992659f827564646ba3ab95ead50adc9' }
        });
        
        if (qrResponse.ok) {
          const qrData = await qrResponse.json();
          console.log('📱 QR Code available - scan it in WhatsApp Web');
          console.log('   Open WhatsApp > Linked Devices > Link a Device');
          console.log('   QR URL: http://localhost:3005/api/default/auth/qr');
          return;
        }
      }
      
      // 5. Test message sending with different methods
      if (defaultSession.status === 'WORKING') {
        console.log('\n5️⃣ Testing different message sending methods...');
        
        const myNumber = defaultSession.me?.id;
        console.log(`   Target number: ${myNumber}`);
        
        // Method 1: Send to self
        console.log('\n   🧪 Method 1: Send to self (safest test)...');
        try {
          const selfMessage = {
            session: 'default',
            chatId: myNumber,
            text: `🧪 SELF TEST ${new Date().toLocaleTimeString()}\n\nIf you receive this, WAHA is working!\n\nFrom: Clinera Debug`
          };
          
          const selfResponse = await fetch('http://localhost:3005/api/sendText', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
              'X-Api-Key': '992659f827564646ba3ab95ead50adc9'
            },
            body: JSON.stringify(selfMessage)
          });
          
          if (selfResponse.ok) {
            const result = await selfResponse.json();
            console.log(`   ✅ Self-message sent: ${result.key?.id}`);
            console.log('      CHECK YOUR WHATSAPP NOW - you should see this message!');
          } else {
            const error = await selfResponse.text();
            console.log(`   ❌ Self-message failed: ${selfResponse.status} - ${error}`);
          }
        } catch (error) {
          console.log(`   ❌ Self-message error: ${error.message}`);
        }
        
        // Method 2: Send with buttons
        console.log('\n   🧪 Method 2: Send with buttons...');
        try {
          const buttonMessage = {
            session: 'default',
            chatId: myNumber,
            title: '🎯 BUTTON TEST MESSAGE',
            buttons: [
              { id: 'test1', text: 'Button 1' },
              { id: 'test2', text: 'Button 2' }
            ],
            footer: 'If you see buttons, advanced messaging works!'
          };
          
          const buttonResponse = await fetch('http://localhost:3005/api/sendButtons', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
              'X-Api-Key': '992659f827564646ba3ab95ead50adc9'
            },
            body: JSON.stringify(buttonMessage)
          });
          
          if (buttonResponse.ok) {
            const result = await buttonResponse.json();
            console.log(`   ✅ Button message sent: ${result.key?.id}`);
          } else {
            const error = await buttonResponse.text();
            console.log(`   ⚠️ Button message failed: ${buttonResponse.status} - ${error}`);
            console.log('      (This is normal if using WAHA Core instead of Plus)');
          }
        } catch (error) {
          console.log(`   ⚠️ Button test error: ${error.message}`);
        }
        
        // Method 3: Check if WhatsApp Web is actually connected
        console.log('\n   🧪 Method 3: Checking WhatsApp Web connection...');
        try {
          const statusResponse = await fetch(`http://localhost:3005/api/default/status`, {
            headers: { 'X-Api-Key': '992659f827564646ba3ab95ead50adc9' }
          });
          
          if (statusResponse.ok) {
            const status = await statusResponse.json();
            console.log('   📱 WhatsApp Status:', JSON.stringify(status, null, 4));
          } else {
            console.log('   ⚠️ Could not get detailed status');
          }
        } catch (error) {
          console.log(`   ⚠️ Status check failed: ${error.message}`);
        }
        
      } else {
        console.log(`❌ Session not working! Status: ${defaultSession.status}`);
        
        if (defaultSession.status === 'STOPPED') {
          console.log('🔧 Trying to start session...');
          
          const startResponse = await fetch(`http://localhost:3005/api/sessions/default/start`, {
            method: 'POST',
            headers: { 'X-Api-Key': '992659f827564646ba3ab95ead50adc9' }
          });
          
          if (startResponse.ok) {
            console.log('✅ Session start initiated');
            console.log('⏳ Wait 10 seconds then check QR code at: http://localhost:3005/api/default/auth/qr');
          } else {
            console.log('❌ Session start failed:', await startResponse.text());
          }
        }
      }
      
    } else {
      console.log('❌ Cannot get session info:', sessionResponse.status);
    }
    
    // 6. Check WAHA logs
    console.log('\n6️⃣ Checking WAHA container logs...');
    try {
      const { execSync } = require('child_process');
      const logs = execSync('docker logs waha --tail 20', { encoding: 'utf8' });
      console.log('📋 Recent WAHA logs:');
      console.log(logs);
    } catch (error) {
      console.log('⚠️ Could not get WAHA logs:', error.message);
    }
    
    console.log('\n🎯 TROUBLESHOOTING STEPS:');
    console.log('1. CHECK YOUR WHATSAPP now for the self-test message');
    console.log('2. If no message: WhatsApp Web might be disconnected');
    console.log('3. Open WhatsApp Web in browser and check if still connected');
    console.log('4. If disconnected, scan QR code again: http://localhost:3005/api/default/auth/qr');
    console.log('5. Make sure WhatsApp app is running on your phone');
    console.log('6. Check phone has internet connection');
    
    console.log('\n🔧 QUICK FIXES TO TRY:');
    console.log('   docker restart waha');
    console.log('   Open http://localhost:3005/api/default/auth/qr in browser');
    console.log('   Scan QR code in WhatsApp > Linked Devices > Link Device');
    
  } catch (error) {
    console.error('❌ Deep debug failed:', error);
  }
}

deepWahaDebug().catch(console.error);