#!/usr/bin/env python
"""
Process all pending M-Pesa callbacks
This script will process all callbacks that haven't been processed yet
"""
import os
import sys
import django
from pathlib import Path

def setup_django():
    """Setup Django environment"""
    script_dir = Path(__file__).resolve().parent
    
    manage_py = script_dir / 'manage.py'
    if not manage_py.exists():
        manage_py = script_dir.parent / 'manage.py'
    
    if manage_py.exists():
        with open(manage_py, 'r') as f:
            content = f.read()
            if 'DJANGO_SETTINGS_MODULE' in content:
                import re
                match = re.search(r"os\.environ\.setdefault\(['\"]DJANGO_SETTINGS_MODULE['\"],\s*['\"]([^'\"]+)['\"]", content)
                if match:
                    os.environ.setdefault('DJANGO_SETTINGS_MODULE', match.group(1))
    
    settings_modules = [
        'config.settings',
        'settings',
        'project.settings',
        'branchsystem.settings',
        'branch_system.settings',
    ]
    
    for settings_module in settings_modules:
        try:
            os.environ.setdefault('DJANGO_SETTINGS_MODULE', settings_module)
            django.setup()
            print(f"✓ Django setup successful with settings: {settings_module}")
            return True
        except Exception as e:
            continue
    
    print("✗ Error: Could not setup Django. Please set DJANGO_SETTINGS_MODULE")
    return False

def process_pending_callbacks():
    """Process all pending M-Pesa callbacks"""
    from payments.models import MpesaCallback
    from payments.services import PaymentProcessor
    from loans.models import MpesaTransaction, Repayment
    
    print("\n" + "="*70)
    print("PROCESSING PENDING M-PESA CALLBACKS")
    print("="*70)
    
    # Find all unprocessed callbacks
    pending_callbacks = MpesaCallback.objects.filter(processed=False).order_by('created_at')
    
    print(f"\nFound {pending_callbacks.count()} pending callbacks")
    
    if pending_callbacks.count() == 0:
        print("\n✓ No pending callbacks to process")
        return
    
    processed_count = 0
    failed_count = 0
    skipped_count = 0
    
    for callback in pending_callbacks:
        print(f"\n{'='*70}")
        print(f"Processing callback: {callback.id}")
        print(f"Created: {callback.created_at}")
        print(f"Type: {callback.callback_type}")
        
        # Check if this callback already has a transaction
        if callback.transaction:
            print(f"  → Callback already has transaction: {callback.transaction.trans_id}")
            # Check if transaction has repayment
            try:
                if callback.transaction.repayment:
                    print(f"  → Transaction already has repayment: {callback.transaction.repayment.receipt_number}")
                    # Mark as processed if repayment exists
                    callback.processed = True
                    callback.save()
                    skipped_count += 1
                    print(f"  ✓ Marked as processed (repayment already exists)")
                    continue
            except:
                pass
        
        # Process the callback
        try:
            # Get raw data
            import json
            if isinstance(callback.raw_data, str):
                callback_data = json.loads(callback.raw_data)
            else:
                callback_data = callback.raw_data
            
            # Process using PaymentProcessor (static method)
            result = PaymentProcessor.process_confirmation_callback(callback_data)
            
            # Refresh callback from database
            callback.refresh_from_db()
            
            if callback.processed:
                print(f"  ✓ Callback processed successfully")
                
                # Check if repayment was created
                if callback.transaction:
                    try:
                        if callback.transaction.repayment:
                            print(f"  ✓ Repayment created: {callback.transaction.repayment.receipt_number}")
                            processed_count += 1
                        else:
                            print(f"  ⚠ Transaction created but no repayment found")
                            print(f"    Transaction status: {callback.transaction.status}")
                            print(f"    Processing notes: {callback.transaction.processing_notes}")
                            failed_count += 1
                    except Exception as e:
                        print(f"  ⚠ Error checking repayment: {e}")
                        failed_count += 1
                else:
                    print(f"  ⚠ Callback processed but no transaction created")
                    failed_count += 1
            else:
                print(f"  ✗ Callback not marked as processed")
                if callback.transaction:
                    print(f"    Transaction status: {callback.transaction.status}")
                    print(f"    Processing notes: {callback.transaction.processing_notes}")
                failed_count += 1
                
        except Exception as e:
            print(f"  ✗ Error processing callback: {e}")
            import traceback
            traceback.print_exc()
            failed_count += 1
    
    print(f"\n{'='*70}")
    print("SUMMARY")
    print("="*70)
    print(f"Total callbacks: {pending_callbacks.count()}")
    print(f"Successfully processed: {processed_count}")
    print(f"Failed: {failed_count}")
    print(f"Skipped (already processed): {skipped_count}")
    print("="*70)

if __name__ == '__main__':
    print("="*70)
    print("PROCESS PENDING M-PESA CALLBACKS")
    print("="*70)
    
    if not setup_django():
        sys.exit(1)
    
    process_pending_callbacks()
    
    print("\n" + "="*70)
    print("DONE")
    print("="*70)

