#!/usr/bin/env python
"""
Production Manual Add Missing Transaction
Run this script on your cPanel production server to manually add the missing transaction
"""
import os
import sys
import django
from decimal import Decimal
from datetime import datetime

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

from loans.models import MpesaTransaction
from users.models import CustomUser as User

def manual_add_missing_transaction():
    """Manually add the missing M-Pesa transaction to production"""
    print("Manually Adding Missing M-Pesa Transaction to Production")
    print("=" * 60)
    
    # Transaction details from your SMS
    transaction_id = "TJ8016VP0B"
    account_number = "40178864"
    phone_number = "+254700000100"
    amount = Decimal("1.00")
    
    print(f"Transaction ID: {transaction_id}")
    print(f"Account Number: {account_number}")
    print(f"Phone Number: {phone_number}")
    print(f"Amount: {amount}")
    print()
    
    # 1. Find the user
    print("1. Finding user in production...")
    user = User.objects.filter(id_number=account_number).first()
    if not user:
        print("❌ User not found in production!")
        return
    
    print(f"✅ Found user: {user.get_full_name()}")
    print(f"   Phone: {user.phone_number}")
    print(f"   ID: {user.id_number}")
    print(f"   Status: {user.status}")
    
    # 2. Check if transaction already exists
    print("\n2. Checking if transaction already exists...")
    existing_transaction = MpesaTransaction.objects.filter(trans_id=transaction_id).first()
    if existing_transaction:
        print(f"⚠️  Transaction already exists: {existing_transaction.id}")
        print(f"   Status: {existing_transaction.status}")
        print(f"   Amount: {existing_transaction.amount}")
        return existing_transaction
    
    # 3. Create the missing transaction
    print("\n3. Creating missing transaction...")
    try:
        transaction = MpesaTransaction.objects.create(
            trans_id=transaction_id,
            transaction_type='c2b',
            amount=amount,
            phone_number=phone_number,
            msisdn=phone_number,
            bill_ref_number=account_number,
            status='confirmed',
            borrower=user,
            is_automatic=True,
            payment_source='automatic',
            processing_notes=f"Manually added to production - account {account_number}",
            raw_confirmation_data={
                'TransID': transaction_id,
                'TransAmount': str(amount),
                'MSISDN': phone_number,
                'BillRefNumber': account_number,
                'TransTime': '20251008062200',  # From your SMS timestamp
                'BusinessShortCode': '4159523',
                'FirstName': user.first_name or '',
                'LastName': user.last_name or '',
            }
        )
        
        print(f"✅ Created transaction: {transaction.id}")
        print(f"   Status: {transaction.status}")
        print(f"   Amount: {transaction.amount}")
        print(f"   Borrower: {transaction.borrower.get_full_name()}")
        
    except Exception as e:
        print(f"❌ Error creating transaction: {e}")
        return None
    
    # 4. Process the payment
    print("\n4. Processing payment...")
    try:
        success = transaction.process_payment()
        
        if success:
            print("✅ Payment processed successfully!")
            transaction.refresh_from_db()
            print(f"   New status: {transaction.status}")
            print(f"   Processing notes: {transaction.processing_notes}")
            
            # Check if repayment was created
            try:
                if hasattr(transaction, 'repayment') and transaction.repayment:
                    print(f"✅ Repayment created: {transaction.repayment.receipt_number}")
                    print(f"   Loan: {transaction.repayment.loan.loan_number}")
                    print(f"   Amount: {transaction.repayment.amount}")
                    print(f"   Payment method: {transaction.repayment.payment_method}")
                    print(f"   Payment source: {transaction.repayment.payment_source}")
                else:
                    print("⚠️  No repayment created")
            except Exception as e:
                print(f"⚠️  Error checking repayment: {e}")
        else:
            print("❌ Payment processing failed")
            transaction.refresh_from_db()
            print(f"   Status: {transaction.status}")
            print(f"   Processing notes: {transaction.processing_notes}")
            
    except Exception as e:
        print(f"❌ Error processing payment: {e}")
    
    print("\nSUMMARY:")
    print("-" * 30)
    print(f"User: {user.get_full_name()}")
    print(f"Transaction: {transaction_id}")
    print(f"Status: {transaction.status}")
    print(f"Amount: {transaction.amount}")
    
    return transaction

if __name__ == "__main__":
    manual_add_missing_transaction()
