"""
Diagnose M-Pesa callback issues
"""
import os
import django

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

from payments.models import MpesaCallback
from loans.models import MpesaTransaction
from users.models import Branch
from datetime import datetime, timedelta

print("=" * 80)
print("M-PESA CALLBACK DIAGNOSTICS")
print("=" * 80)

# 1. Check branch configurations
print("\n1. BRANCH CONFIGURATIONS")
print("-" * 80)
branches = Branch.objects.filter(mpesa_shortcode__isnull=False).exclude(mpesa_shortcode='')
for branch in branches:
    print(f"\n{branch.name} (ID: {branch.id})")
    print(f"  Shortcode: {branch.mpesa_shortcode}")
    print(f"  Consumer Key: {branch.mpesa_consumer_key[:30]}...")
    print(f"  Is Active: {branch.is_active}")

# 2. Check recent callbacks (last 24 hours)
print("\n\n2. RECENT CALLBACKS (Last 24 hours)")
print("-" * 80)
yesterday = datetime.now() - timedelta(hours=24)
recent_callbacks = MpesaCallback.objects.filter(created_at__gte=yesterday).order_by('-created_at')

print(f"\nTotal callbacks received: {recent_callbacks.count()}")

if recent_callbacks.exists():
    for cb in recent_callbacks[:10]:  # Show last 10
        print(f"\n  Time: {cb.created_at}")
        print(f"  Type: {cb.callback_type}")
        print(f"  Processed: {cb.processed}")
        if cb.transaction:
            print(f"  Transaction ID: {cb.transaction.trans_id}")
            print(f"  Transaction Status: {cb.transaction.status}")
        
        # Extract key data from callback
        data = cb.raw_data or {}
        print(f"  Shortcode: {data.get('BusinessShortCode', 'N/A')}")
        print(f"  Trans ID: {data.get('TransID', 'N/A')}")
        print(f"  Amount: {data.get('TransAmount', 'N/A')}")
        print(f"  Account: {data.get('BillRefNumber', 'N/A')}")
else:
    print("\n⚠ NO CALLBACKS received in last 24 hours!")
    print("\nThis means:")
    print("  1. Safaricom is NOT sending callbacks to your server")
    print("  2. Check if callback URLs are registered with Safaricom")
    print("  3. Check server error logs for rejected requests")
    print("  4. Verify SSL certificate is valid")

# 3. Check recent transactions
print("\n\n3. RECENT TRANSACTIONS (Last 24 hours)")
print("-" * 80)
recent_transactions = MpesaTransaction.objects.filter(created_at__gte=yesterday).order_by('-created_at')

print(f"\nTotal transactions: {recent_transactions.count()}")

if recent_transactions.exists():
    for tx in recent_transactions[:10]:
        print(f"\n  Trans ID: {tx.trans_id}")
        print(f"  Time: {tx.created_at}")
        print(f"  Shortcode: {tx.business_short_code}")
        print(f"  Amount: KES {tx.amount}")
        print(f"  Account: {tx.bill_ref_number}")
        print(f"  Status: {tx.status}")
        print(f"  Borrower: {tx.borrower.get_full_name() if tx.borrower else 'Not matched'}")
        print(f"  Loan: {tx.loan.loan_number if tx.loan else 'Not matched'}")
        print(f"  Repayment: {tx.repayment.receipt_number if tx.repayment else 'Not created'}")
        if tx.processing_notes:
            print(f"  Notes: {tx.processing_notes}")
else:
    print("\n⚠ NO TRANSACTIONS recorded!")

# 4. Check for errors in transactions
print("\n\n4. FAILED/PENDING TRANSACTIONS (Last 7 days)")
print("-" * 80)
week_ago = datetime.now() - timedelta(days=7)
failed_transactions = MpesaTransaction.objects.filter(
    created_at__gte=week_ago,
    status__in=['failed', 'pending', 'pending_approval']
).order_by('-created_at')

print(f"\nTotal failed/pending: {failed_transactions.count()}")

if failed_transactions.exists():
    for tx in failed_transactions[:5]:
        print(f"\n  Trans ID: {tx.trans_id}")
        print(f"  Time: {tx.created_at}")
        print(f"  Status: {tx.status}")
        print(f"  Account: {tx.bill_ref_number}")
        print(f"  Notes: {tx.processing_notes or 'No notes'}")

# 5. Test callback URL accessibility
print("\n\n5. CALLBACK URL TEST")
print("-" * 80)
print("\nCallback URLs should be:")
print("  Validation: https://branchbusinessadvance.co.ke/payments/callback/validation/")
print("  Confirmation: https://branchbusinessadvance.co.ke/payments/callback/confirmation/")
print("\nTest with:")
print("  curl -X POST https://branchbusinessadvance.co.ke/payments/callback/confirmation/ \\")
print("    -H 'Content-Type: application/json' \\")
print("    -d '{\"test\":\"data\"}'")

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