#!/usr/bin/env python
"""
Quick check for new payment processing
"""
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 check_payment(trans_id):
    """Check a specific payment"""
    from loans.models import MpesaTransaction
    from payments.models import MpesaCallback
    
    print(f"\nChecking payment: {trans_id}")
    print("="*70)
    
    # Check callback
    callbacks = MpesaCallback.objects.filter(callback_type='confirmation')
    callback = None
    for cb in callbacks:
        if isinstance(cb.raw_data, dict) and cb.raw_data.get('TransID') == trans_id:
            callback = cb
            break
    
    if callback:
        print(f"✓ Callback found: {callback.id}")
        print(f"  Processed: {callback.processed}")
        print(f"  Has transaction: {callback.transaction is not None}")
        if isinstance(callback.raw_data, dict):
            print(f"  Bill Ref: {callback.raw_data.get('BillRefNumber')}")
            print(f"  Amount: {callback.raw_data.get('TransAmount')}")
    else:
        print(f"✗ Callback not found")
        return
    
    # Check transaction
    transaction = MpesaTransaction.objects.filter(trans_id=trans_id).first()
    if transaction:
        print(f"\n✓ Transaction found: {transaction.id}")
        print(f"  Status: {transaction.status}")
        print(f"  Borrower: {transaction.borrower or 'Not matched'}")
        print(f"  Bill Ref: {transaction.bill_ref_number}")
        try:
            repayment = transaction.repayment
            print(f"  Repayment: {repayment.id} ({repayment.receipt_number})")
        except:
            print(f"  Repayment: Not created")
        print(f"  Processing Notes: {transaction.processing_notes or 'None'}")
        
        # Try to process if not processed
        if transaction.status != 'processed':
            print(f"\n  → Attempting to process payment...")
            try:
                success = transaction.process_payment()
                transaction.refresh_from_db()
                
                if success:
                    print(f"  ✓ Payment processed!")
                    try:
                        repayment = transaction.repayment
                        print(f"    Repayment: {repayment.receipt_number}")
                    except:
                        print(f"    ⚠ Repayment created but not linked")
                else:
                    print(f"  ✗ Payment processing failed")
                    print(f"    Status: {transaction.status}")
                    print(f"    Notes: {transaction.processing_notes}")
            except Exception as e:
                print(f"  ✗ Error: {e}")
                import traceback
                traceback.print_exc()
    else:
        print(f"\n✗ Transaction not found")
        print(f"  Creating transaction from callback...")
        try:
            from decimal import Decimal
            data = callback.raw_data
            transaction = MpesaTransaction.objects.create(
                trans_id=data.get('TransID'),
                transaction_type=data.get('TransactionType', 'Pay Bill'),
                amount=Decimal(str(data.get('TransAmount', 0))),
                phone_number=data.get('MSISDN', '')[:17],
                msisdn=data.get('MSISDN', '')[:17],
                trans_time=data.get('TransTime'),
                business_short_code=data.get('BusinessShortCode'),
                bill_ref_number=data.get('BillRefNumber'),
                invoice_number=data.get('InvoiceNumber'),
                org_account_balance=data.get('OrgAccountBalance'),
                third_party_trans_id=data.get('ThirdPartyTransID'),
                first_name=data.get('FirstName'),
                middle_name=data.get('MiddleName'),
                last_name=data.get('LastName'),
                raw_confirmation_data=data,
                status='confirmed',
                is_automatic=True,
                payment_source='automatic'
            )
            callback.transaction = transaction
            callback.save()
            print(f"  ✓ Transaction created: {transaction.id}")
            
            # Process it
            print(f"  → Processing payment...")
            success = transaction.process_payment()
            transaction.refresh_from_db()
            
            if success:
                print(f"  ✓ Payment processed!")
                try:
                    repayment = transaction.repayment
                    print(f"    Repayment: {repayment.receipt_number}")
                except:
                    print(f"    ⚠ Repayment created but not linked")
            else:
                print(f"  ✗ Payment processing failed")
                print(f"    Status: {transaction.status}")
                print(f"    Notes: {transaction.processing_notes}")
        except Exception as e:
            print(f"  ✗ Error: {e}")
            import traceback
            traceback.print_exc()

if __name__ == '__main__':
    if not setup_django():
        sys.exit(1)
    
    check_payment("TK5019CRUK")

