// Emergency fix - restart everything and get it working
async function emergencyFix() {
  console.log('🚨 EMERGENCY FIX - GETTING SYSTEM WORKING AGAIN');
  console.log('='.repeat(60));
  
  console.log('😤 I UNDERSTAND YOU\'RE MAD - IT WAS WORKING!');
  console.log('🔧 Let\'s fix this RIGHT NOW with nuclear option...');
  console.log('');
  
  try {
    // Step 1: Restart WAHA container completely
    console.log('1️⃣ RESTARTING WAHA CONTAINER...');
    const { execSync } = require('child_process');
    
    try {
      console.log('   Stopping WAHA...');
      execSync('docker stop waha', { stdio: 'ignore' });
      
      console.log('   Starting WAHA...');
      execSync('docker start waha', { stdio: 'ignore' });
      
      console.log('   ✅ WAHA restarted');
      
      // Wait for startup
      console.log('   ⏳ Waiting 15 seconds for WAHA to start...');
      await new Promise(resolve => setTimeout(resolve, 15000));
      
    } catch (dockerError) {
      console.log('   ⚠️ Docker restart failed, continuing anyway...');
    }
    
    // Step 2: Check if WAHA is responding
    console.log('\n2️⃣ CHECKING WAHA STATUS...');
    
    let wahaWorking = false;
    try {
      const response = await fetch('http://localhost:3005/api/sessions', {
        headers: { 'X-Api-Key': '992659f827564646ba3ab95ead50adc9' }
      });
      
      if (response.ok) {
        const sessions = await response.json();
        console.log(`   ✅ WAHA responding, ${sessions.length} sessions found`);
        wahaWorking = true;
        
        const defaultSession = sessions.find(s => s.name === 'default');
        if (defaultSession) {
          console.log(`   📱 Session status: ${defaultSession.status}`);
          
          if (defaultSession.status === 'SCAN_QR_CODE') {
            console.log('   🚨 QR CODE NEEDED! This is why it stopped working!');
            console.log('   🔗 Scan QR code at: http://localhost:3005/api/default/auth/qr');
            console.log('   📱 WhatsApp > Settings > Linked Devices > Link Device');
            return;
          }
        }
      } else {
        console.log('   ❌ WAHA not responding properly');
      }
    } catch (error) {
      console.log('   ❌ WAHA connection failed:', error.message);
    }
    
    if (!wahaWorking) {
      console.log('\n🚨 WAHA NOT WORKING - TRY THIS:');
      console.log('   docker restart waha');
      console.log('   Then: http://localhost:3005/api/default/auth/qr');
      return;
    }
    
    // Step 3: Send immediate test
    console.log('\n3️⃣ SENDING IMMEDIATE TEST MESSAGE...');
    
    const sessionResponse = await fetch('http://localhost:3005/api/sessions', {
      headers: { 'X-Api-Key': '992659f827564646ba3ab95ead50adc9' }
    });
    
    if (sessionResponse.ok) {
      const sessions = await sessionResponse.json();
      const defaultSession = sessions.find(s => s.name === 'default');
      
      if (defaultSession && defaultSession.status === 'WORKING') {
        const testMessage = {
          session: 'default',
          chatId: defaultSession.me?.id,
          text: `🔧 EMERGENCY FIX TEST

Time: ${new Date().toLocaleString()}

OBAID - if you see this message, the system is working again!

This proves:
✅ WAHA is back online
✅ WhatsApp is connected  
✅ Messages can be delivered

The issue was likely WhatsApp Web disconnection or WAHA restart needed.

Reply "FIXED" if you see this!`
        };
        
        const sendResponse = await fetch('http://localhost:3005/api/sendText', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'X-Api-Key': '992659f827564646ba3ab95ead50adc9'
          },
          body: JSON.stringify(testMessage)
        });
        
        if (sendResponse.ok) {
          const result = await sendResponse.json();
          console.log(`   🎉 EMERGENCY TEST SENT: ${result.key?.id}`);
          console.log(`   📱 To: ${defaultSession.me?.pushName}`);
          console.log('   📞 CHECK YOUR WHATSAPP NOW!');
          
          // Step 4: Test Clinera system
          console.log('\n4️⃣ TESTING CLINERA REMINDER SYSTEM...');
          
          const cronResponse = await fetch('http://localhost:3000/api/cron/send-reminders?key=dev-cron-key', {
            method: 'POST'
          });
          
          if (cronResponse.ok) {
            const cronResult = await cronResponse.json();
            console.log(`   ✅ Clinera cron working: sent=${cronResult.sent}, failed=${cronResult.failed}`);
          } else {
            console.log(`   ⚠️ Clinera cron issue: ${cronResponse.status}`);
          }
          
          console.log('\n🎉 EMERGENCY FIX COMPLETE!');
          console.log('='.repeat(40));
          console.log('✅ WAHA restarted');
          console.log('✅ Session working');  
          console.log('✅ Test message sent');
          console.log('✅ Clinera system tested');
          console.log('');
          console.log('📱 OBAID - CHECK YOUR WHATSAPP!');
          console.log('   If you see the emergency test message,');
          console.log('   the reminder system is working again!');
          
        } else {
          console.log('   ❌ Test message failed:', await sendResponse.text());
        }
        
      } else {
        console.log(`   ❌ Session not working: ${defaultSession?.status || 'no session'}`);
        
        if (defaultSession?.status === 'SCAN_QR_CODE') {
          console.log('\n🚨 QR CODE SCAN REQUIRED:');
          console.log('   1. Open: http://localhost:3005/api/default/auth/qr');
          console.log('   2. WhatsApp > Settings > Linked Devices > Link Device');
          console.log('   3. Scan the QR code');
          console.log('   4. Wait for "WORKING" status');
        }
      }
    }
    
  } catch (error) {
    console.error('❌ Emergency fix failed:', error);
    
    console.log('\n🚨 MANUAL EMERGENCY STEPS:');
    console.log('1. docker restart waha');
    console.log('2. Wait 30 seconds');
    console.log('3. Open: http://localhost:3005/api/default/auth/qr');
    console.log('4. Scan QR code in WhatsApp');
    console.log('5. Test again');
  }
}

emergencyFix().catch(console.error);