"""
Diagnostic script to check why SasaPay IPNs are not creating automatic payments.
Run this to see:
1. Recent IPN logs and their processing status
2. Manual vs Auto payments breakdown
3. Matching failures and reasons
"""

import os
import django
import sys
from pathlib import Path

# Setup Django
BASE_DIR = Path(__file__).resolve().parent
sys.path.insert(0, str(BASE_DIR))
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from django.utils import timezone
from datetime import timedelta
from payments.sasapay_models import SasaPayIPNLog
from loans.models import Repayment
from django.db.models import Count, Q

def main():
    print("\n" + "="*80)
    print("SASAPAY IPN DIAGNOSTIC REPORT")
    print("="*80)
    
    # Check recent IPNs (last 7 days)
    seven_days_ago = timezone.now() - timedelta(days=7)
    recent_ipns = SasaPayIPNLog.objects.filter(created_at__gte=seven_days_ago)
    
    print(f"\n📊 IPN LOGS (Last 7 days)")
    print("-" * 80)
    print(f"Total IPNs received: {recent_ipns.count()}")
    
    if recent_ipns.count() == 0:
        print("\n⚠️  NO IPNs RECEIVED IN LAST 7 DAYS!")
        print("\nThis means SasaPay is NOT sending payment notifications to your webhook.")
        print("\n🔧 ACTION REQUIRED:")
        print("   1. Login to SasaPay Merchant Portal")
        print("   2. Go to Settings/Configuration > IPN/Callback URLs")
        print("   3. Set IPN URL to: https://grazuri.uzuriapps.xyz/payments/sasapay/ipn/")
        print("   4. Ensure URL is verified and active\n")
    else:
        # Break down by status
        status_breakdown = recent_ipns.values('processing_status').annotate(count=Count('id'))
        print("\nProcessing Status Breakdown:")
        for status in status_breakdown:
            status_name = status['processing_status']
            count = status['count']
            print(f"   {status_name.upper()}: {count}")
        
        # Show failed/problematic IPNs
        problem_ipns = recent_ipns.exclude(
            processing_status__in=['processed', 'duplicate']
        ).order_by('-created_at')[:10]
        
        if problem_ipns.exists():
            print(f"\n⚠️  PROBLEMATIC IPNs (showing last 10):")
            print("-" * 80)
            for ipn in problem_ipns:
                trans_id = ipn.trans_id or str(ipn.id)[:8]
                amount = ipn.raw_data.get('TransAmount', 'N/A')
                bill_ref = ipn.raw_data.get('BillRefNumber', 'N/A')
                name = f"{ipn.raw_data.get('FirstName', '')} {ipn.raw_data.get('LastName', '')}".strip()
                
                print(f"\n   TransID: {trans_id}")
                print(f"   Amount: KES {amount}")
                print(f"   BillRef: {bill_ref}")
                print(f"   Name: {name}")
                print(f"   Status: {ipn.processing_status}")
                print(f"   Reason: {ipn.processing_note}")
                print(f"   Time: {ipn.created_at.strftime('%Y-%m-%d %H:%M:%S')}")
    
    # Check payment source breakdown (last 30 days)
    print("\n\n📊 PAYMENTS BREAKDOWN (Last 30 days)")
    print("-" * 80)
    thirty_days_ago = timezone.now() - timedelta(days=30)
    recent_payments = Repayment.objects.filter(created_at__gte=thirty_days_ago)
    
    total_payments = recent_payments.count()
    auto_payments = recent_payments.filter(payment_source='automatic').count()
    manual_payments = recent_payments.filter(payment_source='manual').count()
    
    print(f"Total Payments: {total_payments}")
    print(f"   ⚡ Automatic (SasaPay): {auto_payments} ({auto_payments*100//total_payments if total_payments else 0}%)")
    print(f"   ✋ Manual Entry: {manual_payments} ({manual_payments*100//total_payments if total_payments else 0}%)")
    
    # Check webhook accessibility
    print("\n\n🌐 WEBHOOK CONFIGURATION")
    print("-" * 80)
    from django.conf import settings
    site_url = settings.SITE_URL
    ipn_url = f"{site_url}/payments/sasapay/ipn/"
    print(f"Expected IPN URL: {ipn_url}")
    print(f"Merchant Code: {settings.SASAPAY_MERCHANT_CODE}")
    print(f"Network Code: {settings.SASAPAY_NETWORK_CODE}")
    
    # Test webhook URL accessibility
    print("\n🔍 Testing webhook URL accessibility...")
    try:
        import requests
        response = requests.get(ipn_url, timeout=10)
        if response.status_code == 200:
            print(f"   ✅ Webhook URL is accessible (Status: {response.status_code})")
        else:
            print(f"   ⚠️  Webhook returned status: {response.status_code}")
    except requests.exceptions.RequestException as e:
        print(f"   ❌ Webhook NOT accessible: {e}")
        print("   This could be why SasaPay cannot send IPNs!")
    
    # Recent automatic payments (show they DO work when IPNs arrive)
    print("\n\n✅ RECENT AUTOMATIC PAYMENTS (Last 10)")
    print("-" * 80)
    auto_recent = Repayment.objects.filter(
        payment_source='automatic'
    ).order_by('-created_at')[:10]
    
    if auto_recent.exists():
        for rep in auto_recent:
            print(f"\n   Receipt: {rep.receipt_number}")
            print(f"   Loan: {rep.loan.loan_number}")
            print(f"   Borrower: {rep.loan.borrower.get_full_name()}")
            print(f"   Amount: KES {rep.amount}")
            print(f"   TransID: {rep.mpesa_transaction_id}")
            print(f"   Date: {rep.payment_date.strftime('%Y-%m-%d %H:%M:%S')}")
    else:
        print("   No automatic payments found")
        print("   This suggests IPNs are NOT being processed successfully")
    
    print("\n\n" + "="*80)
    print("RECOMMENDATIONS:")
    print("="*80)
    
    if recent_ipns.count() == 0:
        print("""
1. 🚨 PRIMARY ISSUE: No IPNs are being received
   - SasaPay is not sending payment notifications to your server
   - Action: Register IPN URL in SasaPay Merchant Portal
   
2. Verify IPN URL in SasaPay Portal:
   URL: https://grazuri.uzuriapps.xyz/payments/sasapay/ipn/
   
3. Test the webhook:
   - Make a test payment through SasaPay
   - Check if IPN arrives at /payments/sasapay/ipn-gaps/
   
4. If IPNs still don't arrive:
   - Check firewall settings
   - Verify domain SSL certificate is valid
   - Check SasaPay portal for delivery errors
        """)
    else:
        problem_count = recent_ipns.exclude(
            processing_status__in=['processed', 'duplicate']
        ).count()
        
        if problem_count > 0:
            print(f"""
1. ⚠️  {problem_count} IPNs failed to create payments
   - Check reasons in the 'PROBLEMATIC IPNs' section above
   - Common issues:
     * Phone number format mismatches
     * Borrower not found in system
     * No active loan for borrower
     
2. View detailed logs in admin:
   URL: https://grazuri.uzuriapps.xyz/payments/sasapay/ipn-gaps/
   
3. Fix matching issues:
   - Ensure borrower phone numbers match BillRef format
   - Consider adding ID number or loan number to BillRef
            """)
        else:
            print("""
✅ System is working correctly!
   - IPNs are being received
   - Payments are being processed automatically
   
If you're still seeing manual payments:
   - Those are being entered by staff manually
   - Not related to SasaPay automation
            """)
    
    print("\n" + "="*80 + "\n")

if __name__ == '__main__':
    main()
