"""
Diagnostic script to check M-Pesa configuration for both branches
"""
import os
import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from users.models import Branch
from payments.models import MpesaConfiguration, MpesaCallback
from loans.models import MpesaTransaction
from django.db.models import Count

print("=" * 80)
print("M-PESA CONFIGURATION DIAGNOSTIC")
print("=" * 80)

# Check branches
branches = Branch.objects.all()
print(f"\n1. BRANCH CONFIGURATION")
print("-" * 80)
for branch in branches:
    print(f"\nBranch: {branch.name} (Code: {branch.code})")
    print(f"  - Main Branch: {branch.is_main_branch}")
    print(f"  - M-Pesa Shortcode: {branch.mpesa_shortcode or 'NOT SET'}")
    print(f"  - Consumer Key: {branch.mpesa_consumer_key[:20] + '...' if branch.mpesa_consumer_key else 'NOT SET'}")
    print(f"  - Consumer Secret: {branch.mpesa_consumer_secret[:20] + '...' if branch.mpesa_consumer_secret else 'NOT SET'}")
    print(f"  - Active: {branch.is_active}")

# Check M-Pesa configuration
print(f"\n2. GLOBAL M-PESA CONFIGURATION")
print("-" * 80)
configs = MpesaConfiguration.objects.all()
for config in configs:
    print(f"\nEnvironment: {config.environment}")
    print(f"  - Shortcode: {config.business_short_code}")
    print(f"  - Consumer Key: {config.consumer_key[:20]}...")
    print(f"  - Validation URL: {config.validation_url}")
    print(f"  - Confirmation URL: {config.confirmation_url}")
    print(f"  - Active: {config.is_active}")

# Check recent transactions by shortcode
print(f"\n3. RECENT TRANSACTIONS BY SHORTCODE")
print("-" * 80)
shortcode_stats = MpesaTransaction.objects.values('business_short_code').annotate(
    total=Count('id')
).order_by('-total')

for stat in shortcode_stats:
    shortcode = stat['business_short_code'] or 'NULL'
    count = stat['total']
    print(f"\nShortcode {shortcode}: {count} transactions")
    
    # Get recent transactions
    recent = MpesaTransaction.objects.filter(
        business_short_code=stat['business_short_code']
    ).order_by('-created_at')[:5]
    
    for txn in recent:
        print(f"  - {txn.trans_id}: KES {txn.amount} ({txn.status}) - {txn.created_at.strftime('%Y-%m-%d %H:%M')}")

# Check callback statistics
print(f"\n4. CALLBACK STATISTICS")
print("-" * 80)
callback_count = MpesaCallback.objects.count()
processed_count = MpesaCallback.objects.filter(processed=True).count()
print(f"Total Callbacks: {callback_count}")
print(f"Processed: {processed_count}")
print(f"Pending: {callback_count - processed_count}")

recent_callbacks = MpesaCallback.objects.order_by('-created_at')[:10]
print("\nRecent Callbacks:")
for cb in recent_callbacks:
    shortcode = cb.raw_data.get('BusinessShortCode', 'N/A') if cb.raw_data else 'N/A'
    print(f"  - {cb.callback_type} | Shortcode: {shortcode} | Processed: {cb.processed} | {cb.created_at.strftime('%Y-%m-%d %H:%M')}")

print("\n" + "=" * 80)
print("DIAGNOSTIC COMPLETE")
print("=" * 80)

print("\n\nRECOMMENDATIONS:")
print("-" * 80)

# Check if branches have proper config
main_branch = branches.filter(is_main_branch=True).first()
juja_branch = branches.filter(code='002').first()

if main_branch:
    if not main_branch.mpesa_shortcode:
        print("⚠ WARNING: Main branch has no M-Pesa shortcode configured!")
    else:
        print(f"✓ Main branch shortcode: {main_branch.mpesa_shortcode}")
        
        # Check if we've received any payments for this shortcode
        main_txns = MpesaTransaction.objects.filter(business_short_code=main_branch.mpesa_shortcode).count()
        if main_txns == 0:
            print(f"  ⚠ No transactions received for Main branch shortcode {main_branch.mpesa_shortcode}")
            print(f"    POSSIBLE CAUSES:")
            print(f"    1. Callback URLs not registered with Safaricom for this shortcode")
            print(f"    2. No payments have been made to this paybill yet")
            print(f"    3. Paybill is not active")
        else:
            print(f"  ✓ {main_txns} transactions received for Main branch")

if juja_branch:
    if not juja_branch.mpesa_shortcode:
        print("⚠ WARNING: Juja branch has no M-Pesa shortcode configured!")
    else:
        print(f"✓ Juja branch shortcode: {juja_branch.mpesa_shortcode}")
        juja_txns = MpesaTransaction.objects.filter(business_short_code=juja_branch.mpesa_shortcode).count()
        print(f"  ✓ {juja_txns} transactions received for Juja branch")

print("\nNEXT STEPS:")
print("1. Verify callback URLs are registered with Safaricom for BOTH shortcodes")
print("2. Test payment to Main branch paybill (4086675)")
print("3. Check Safaricom portal for any error messages")
print("4. Ensure both paybills are active and accepting payments")
