
from django.core.management.base import BaseCommand
from payments.services import MpesaService
from settings.models import SystemSettings
import requests

class Command(BaseCommand):
    help = 'Test M-Pesa configuration and credentials'

    def handle(self, *args, **options):
        self.stdout.write("Testing M-Pesa Configuration...")
        self.stdout.write("=" * 50)
        
        # Check settings
        mpesa_settings = SystemSettings.get_mpesa_settings()
        
        self.stdout.write("M-Pesa Settings:")
        for key, value in mpesa_settings.items():
            if key in ['consumer_secret', 'passkey']:
                display_value = '*' * len(value) if value else 'Not Set'
            else:
                display_value = value if value else 'Not Set'
            self.stdout.write(f"  {key}: {display_value}")
        
        self.stdout.write("\n" + "=" * 50)
        
        # Validate settings
        missing_settings = []
        if not mpesa_settings.get('consumer_key'):
            missing_settings.append('consumer_key')
        if not mpesa_settings.get('consumer_secret'):
            missing_settings.append('consumer_secret')
        if not mpesa_settings.get('business_short_code'):
            missing_settings.append('business_short_code')
        if not mpesa_settings.get('passkey'):
            missing_settings.append('passkey')
            
        if missing_settings:
            self.stdout.write(
                self.style.ERROR(f"❌ Missing required settings: {', '.join(missing_settings)}")
            )
            return
            
        # Test internet connectivity
        self.stdout.write("Testing internet connectivity...")
        try:
            response = requests.get('https://www.google.com', timeout=10)
            if response.status_code == 200:
                self.stdout.write(self.style.SUCCESS("✅ Internet connectivity OK"))
            else:
                self.stdout.write(self.style.ERROR("❌ Limited internet connectivity"))
        except Exception as e:
            self.stdout.write(self.style.ERROR(f"❌ No internet connectivity: {str(e)}"))
            return
        
        # Test M-Pesa service
        mpesa_service = MpesaService()
        
        self.stdout.write(f"Testing access token for {mpesa_service.environment} environment...")
        self.stdout.write(f"API Base URL: {mpesa_service.base_url}")
        
        access_token = mpesa_service.get_access_token()
        
        if access_token:
            self.stdout.write(
                self.style.SUCCESS("✅ Access token obtained successfully!")
            )
            self.stdout.write(f"Token preview: {access_token[:20]}...")
            
            # Test if we can make additional requests
            self.stdout.write("\nTesting API endpoint availability...")
            try:
                test_url = f"{mpesa_service.base_url}/mpesa/c2b/v1/registerurl"
                headers = {'Authorization': f'Bearer {access_token}'}
                test_response = requests.post(test_url, headers=headers, json={}, timeout=30)
                if test_response.status_code in [200, 400]:  # 400 is expected with empty payload
                    self.stdout.write(self.style.SUCCESS("✅ M-Pesa API endpoints are accessible"))
                else:
                    self.stdout.write(self.style.WARNING(f"⚠️ API endpoint test returned: {test_response.status_code}"))
            except Exception as e:
                self.stdout.write(self.style.ERROR(f"❌ API endpoint test failed: {str(e)}"))
        else:
            self.stdout.write(
                self.style.ERROR("❌ Failed to get access token - Check your credentials and network connection")
            )
        
        self.stdout.write("=" * 50)
        
        # Test C2B URL registration if access token works
        if access_token:
            self.stdout.write("\nTesting C2B URL registration...")
            try:
                # Test with dummy URLs
                test_validation_url = "https://your-domain.com/payments/mpesa-paybill-callback/"
                test_confirmation_url = "https://your-domain.com/payments/mpesa-paybill-callback/"
                
                registration_response = mpesa_service.register_c2b_urls(
                    test_validation_url, 
                    test_confirmation_url
                )
                
                if registration_response.get('ResponseCode') == '0':
                    self.stdout.write(self.style.SUCCESS("✅ C2B URL registration test successful"))
                else:
                    error_msg = registration_response.get('errorMessage', registration_response.get('ResponseDescription', 'Unknown error'))
                    if 'Invalid Access Token' in error_msg:
                        self.stdout.write(self.style.WARNING("⚠️ Access token is invalid for C2B registration"))
                        self.stdout.write("This usually means your M-Pesa app is not approved for production")
                        self.stdout.write("or your credentials don't match the selected environment")
                    else:
                        self.stdout.write(self.style.ERROR(f"❌ C2B URL registration failed: {error_msg}"))
                        
            except Exception as e:
                self.stdout.write(self.style.ERROR(f"❌ C2B URL registration test failed: {str(e)}"))
        
        self.stdout.write("=" * 50)
        self.stdout.write("Configuration test completed!")
