#!/usr/bin/env python
"""
Process a specific M-Pesa payment by transaction ID
"""
import os
import sys
import django
from pathlib import Path

def setup_django():
    """Setup Django environment"""
    script_dir = Path(__file__).resolve().parent
    
    # Add script directory to path
    sys.path.insert(0, str(script_dir))
    
    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

# Setup Django
if not setup_django():
    sys.exit(1)

from loans.models import MpesaTransaction
from payments.models import MpesaCallback
from payments.services import PaymentProcessor
import json

def process_specific_payment(trans_id):
    """Process a specific payment by transaction ID"""
    print("=" * 70)
    print(f"PROCESSING PAYMENT: {trans_id}")
    print("=" * 70)
    
    # Find the transaction
    transaction = MpesaTransaction.objects.filter(trans_id=trans_id).first()
    if not transaction:
        print(f"✗ Transaction {trans_id} not found")
        return False
    
    print(f"✓ Transaction found: {transaction.id}")
    print(f"  Status: {transaction.status}")
    print(f"  Amount: KES {transaction.amount}")
    print(f"  Bill Ref: {transaction.bill_ref_number}")
    print(f"  Phone: {transaction.msisdn or transaction.phone_number}")
    
    # Check for existing repayment
    if transaction.repayment:
        print(f"✓ Payment already processed! Repayment: {transaction.repayment.receipt_number}")
        return True
    
    # Find the callback
    callback = MpesaCallback.objects.filter(
        transaction=transaction,
        callback_type='confirmation'
    ).first()
    
    if callback:
        print(f"✓ Callback found: {callback.id}")
        print(f"  Processed: {callback.processed}")
        
        # Process using the callback data
        if callback.raw_data:
            print("\n" + "-" * 70)
            print("PROCESSING FROM CALLBACK DATA")
            print("-" * 70)
            try:
                response = PaymentProcessor.process_confirmation_callback(callback.raw_data)
                callback.refresh_from_db()
                transaction.refresh_from_db()
                
                print(f"\nCallback processed: {callback.processed}")
                print(f"Transaction status: {transaction.status}")
                
                if transaction.repayment:
                    print(f"✓ Payment processed successfully!")
                    print(f"  Repayment: {transaction.repayment.receipt_number}")
                    print(f"  Amount: KES {transaction.repayment.amount}")
                    return True
                else:
                    print(f"✗ Payment not processed")
                    print(f"  Processing notes: {transaction.processing_notes}")
                    return False
            except Exception as e:
                print(f"✗ Error processing callback: {str(e)}")
                import traceback
                traceback.print_exc()
                return False
    else:
        # No callback - try to process directly
        print("\n" + "-" * 70)
        print("NO CALLBACK FOUND - PROCESSING TRANSACTION DIRECTLY")
        print("-" * 70)
        
        try:
            success = transaction.process_payment()
            transaction.refresh_from_db()
            
            if success and transaction.repayment:
                print(f"✓ Payment processed successfully!")
                print(f"  Repayment: {transaction.repayment.receipt_number}")
                print(f"  Amount: KES {transaction.repayment.amount}")
                return True
            else:
                print(f"✗ Payment not processed")
                print(f"  Status: {transaction.status}")
                print(f"  Processing notes: {transaction.processing_notes}")
                return False
        except Exception as e:
            print(f"✗ Error processing transaction: {str(e)}")
            import traceback
            traceback.print_exc()
            return False

if __name__ == '__main__':
    if len(sys.argv) > 1:
        trans_id = sys.argv[1]
    else:
        # Default to the payment the user mentioned
        trans_id = 'TK5019D45L'
    
    success = process_specific_payment(trans_id)
    
    print("\n" + "=" * 70)
    if success:
        print("✓ PAYMENT PROCESSED SUCCESSFULLY")
    else:
        print("✗ PAYMENT PROCESSING FAILED")
    print("=" * 70)

