
import json
from django.core.management.base import BaseCommand
from django.utils import timezone
from payments.models import Payment, UnreconciledPayment
from customers.models import Customer
from settings.models import SystemSettings
from payments.services import MpesaService

class Command(BaseCommand):
    help = 'Debug M-Pesa payment issues'

    def handle(self, *args, **options):
        self.stdout.write("=== M-Pesa Payment System Diagnostics ===\n")
        
        # 1. Check M-Pesa configuration
        self.stdout.write("1. Checking M-Pesa Configuration...")
        mpesa_settings = SystemSettings.get_mpesa_settings()
        
        required_settings = ['consumer_key', 'consumer_secret', 'business_short_code', 'passkey', 'callback_url']
        missing_settings = []
        
        for setting in required_settings:
            if not mpesa_settings.get(setting):
                missing_settings.append(setting)
        
        if missing_settings:
            self.stdout.write(self.style.ERROR(f"❌ Missing M-Pesa settings: {', '.join(missing_settings)}"))
            self.stdout.write("Please configure these in Settings > System Settings\n")
        else:
            self.stdout.write(self.style.SUCCESS("✅ M-Pesa configuration complete"))
            self.stdout.write(f"Callback URL: {mpesa_settings.get('callback_url')}")
            self.stdout.write(f"Environment: {mpesa_settings.get('environment', 'sandbox')}\n")
        
        # 2. Test M-Pesa connectivity
        self.stdout.write("2. Testing M-Pesa API Connectivity...")
        try:
            mpesa_service = MpesaService()
            access_token = mpesa_service.get_access_token()
            if access_token:
                self.stdout.write(self.style.SUCCESS("✅ M-Pesa API connection successful"))
            else:
                self.stdout.write(self.style.ERROR("❌ Failed to get M-Pesa access token"))
        except Exception as e:
            self.stdout.write(self.style.ERROR(f"❌ M-Pesa API Error: {str(e)}"))
        
        # 3. Check recent payments
        self.stdout.write("\n3. Recent Payment Activity...")
        recent_payments = Payment.objects.filter(
            payment_method='mpesa',
            created_at__gte=timezone.now() - timezone.timedelta(days=7)
        ).order_by('-created_at')[:5]
        
        if recent_payments:
            self.stdout.write(f"✅ Found {recent_payments.count()} recent M-Pesa payments:")
            for payment in recent_payments:
                self.stdout.write(f"  - {payment.payment_id}: KES {payment.amount} ({payment.status}) - {payment.created_at}")
        else:
            self.stdout.write(self.style.WARNING("⚠️ No recent M-Pesa payments found"))
        
        # 4. Check unreconciled payments
        self.stdout.write("\n4. Checking Unreconciled Payments...")
        unreconciled = UnreconciledPayment.objects.filter(status='pending').count()
        if unreconciled > 0:
            self.stdout.write(self.style.WARNING(f"⚠️ {unreconciled} unreconciled payments need attention"))
            self.stdout.write("Check: /payments/unreconciled/")
        else:
            self.stdout.write(self.style.SUCCESS("✅ No pending unreconciled payments"))
        
        # 5. Check customer phone format consistency
        self.stdout.write("\n5. Checking Customer Phone Format Consistency...")
        customers_with_phones = Customer.objects.exclude(phone__isnull=True).exclude(phone='')
        phone_formats = {}
        
        for customer in customers_with_phones:
            phone = customer.phone
            if phone.startswith('+254'):
                phone_formats['international'] = phone_formats.get('international', 0) + 1
            elif phone.startswith('254'):
                phone_formats['country_code'] = phone_formats.get('country_code', 0) + 1
            elif phone.startswith('0'):
                phone_formats['local'] = phone_formats.get('local', 0) + 1
            else:
                phone_formats['other'] = phone_formats.get('other', 0) + 1
        
        self.stdout.write(f"Phone number formats in database:")
        for format_type, count in phone_formats.items():
            self.stdout.write(f"  - {format_type}: {count} customers")
        
        self.stdout.write(f"\n=== Diagnostics Complete ===")
        self.stdout.write("If payments are still not working:")
        self.stdout.write("1. Check server logs for M-Pesa callback errors")
        self.stdout.write("2. Verify callback URL is publicly accessible")
        self.stdout.write("3. Test STK push with a known customer phone number")
        self.stdout.write("4. Check /payments/unreconciled/ for pending payments")
