#!/usr/bin/env python
"""
Production Create Repayment Manually
Run this script on your cPanel production server to manually create the repayment
"""
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, Repayment
from users.models import CustomUser as User

def create_repayment_manually():
    """Manually create repayment for the missing transaction"""
    print("Creating Repayment Manually for Missing Transaction")
    print("=" * 60)
    
    transaction_id = "TJ8016VP0B"
    
    # Find the transaction
    transaction = MpesaTransaction.objects.filter(trans_id=transaction_id).first()
    if not transaction:
        print(f"❌ Transaction {transaction_id} not found!")
        return
    
    print(f"Found transaction: {transaction.id}")
    print(f"Status: {transaction.status}")
    print(f"Amount: {transaction.amount}")
    print(f"Borrower: {transaction.borrower.get_full_name()}")
    print(f"Phone: {transaction.phone_number}")
    
    # Get user's active loan
    user = transaction.borrower
    active_loans = user.loans.filter(status='active')
    
    if not active_loans.exists():
        print("❌ No active loans found for user!")
        return
    
    loan = active_loans.first()
    print(f"\nUsing loan: {loan.loan_number}")
    print(f"Loan amount: {loan.total_amount}")
    print(f"Outstanding: {loan.outstanding_amount}")
    
    # Check if repayment already exists
    existing_repayment = Repayment.objects.filter(
        loan=loan,
        amount=transaction.amount,
        mpesa_transaction_id=transaction.trans_id
    ).first()
    
    if existing_repayment:
        print(f"\n⚠️  Repayment already exists: {existing_repayment.receipt_number}")
        print(f"Amount: {existing_repayment.amount}")
        print(f"Date: {existing_repayment.payment_date}")
        return existing_repayment
    
    # Create repayment with unique receipt number
    print("\nCreating repayment...")
    try:
        # Generate unique receipt number
        timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
        receipt_number = f"RCP-{timestamp}"
        
        # Ensure receipt number is unique
        counter = 1
        while Repayment.objects.filter(receipt_number=receipt_number).exists():
            receipt_number = f"RCP-{timestamp}-{counter}"
            counter += 1
        
        print(f"Using receipt number: {receipt_number}")
        
        # Create the repayment
        repayment = Repayment.objects.create(
            loan=loan,
            amount=transaction.amount,
            payment_method='mpesa',
            payment_source='automatic',
            mpesa_transaction_id=transaction.trans_id,
            mpesa_phone_number=transaction.phone_number,
            payment_date=transaction.created_at,
            receipt_number=receipt_number
        )
        
        print(f"✅ Created repayment: {repayment.receipt_number}")
        print(f"   Amount: {repayment.amount}")
        print(f"   Payment method: {repayment.payment_method}")
        print(f"   Payment source: {repayment.payment_source}")
        print(f"   Payment date: {repayment.payment_date}")
        print(f"   Loan: {repayment.loan.loan_number}")
        
        # Link transaction to repayment
        transaction.repayment = repayment
        transaction.save()
        
        print(f"\n✅ Linked transaction to repayment")
        print(f"Transaction status: {transaction.status}")
        
        # Update loan outstanding amount
        loan.refresh_from_db()
        print(f"Updated loan outstanding: {loan.outstanding_amount}")
        
        return repayment
        
    except Exception as e:
        print(f"❌ Error creating repayment: {e}")
        return None

def verify_repayment():
    """Verify the repayment was created correctly"""
    print("\nVerifying repayment...")
    
    transaction_id = "TJ8016VP0B"
    transaction = MpesaTransaction.objects.filter(trans_id=transaction_id).first()
    
    if not transaction:
        print("❌ Transaction not found!")
        return
    
    try:
        if hasattr(transaction, 'repayment') and transaction.repayment:
            repayment = transaction.repayment
            print(f"✅ Repayment verified: {repayment.receipt_number}")
            print(f"   Amount: {repayment.amount}")
            print(f"   Loan: {repayment.loan.loan_number}")
            print(f"   Payment method: {repayment.payment_method}")
            print(f"   Payment source: {repayment.payment_source}")
            
            # Check if it appears in repayments list
            from loans.models import Repayment
            all_repayments = Repayment.objects.filter(
                loan__borrower=transaction.borrower
            ).order_by('-payment_date')
            
            print(f"\nAll repayments for {transaction.borrower.get_full_name()}:")
            for r in all_repayments[:5]:
                print(f"  {r.receipt_number} - {r.amount} - {r.payment_date} - {r.payment_source}")
                
        else:
            print("❌ No repayment linked to transaction")
            
    except Exception as e:
        print(f"❌ Error verifying repayment: {e}")

if __name__ == "__main__":
    repayment = create_repayment_manually()
    if repayment:
        verify_repayment()
        
        print("\n" + "="*60)
        print("SUCCESS!")
        print("✅ Transaction TJ8016VP0B has been processed")
        print("✅ Repayment created and linked")
        print("✅ Payment should now appear in /loans/repayments/")
        print("✅ Loan outstanding amount updated")
    else:
        print("\n❌ Failed to create repayment")



