#!/usr/bin/env python3
"""
Test the rollover update logic locally
Creates test data, simulates rollover approval, verifies it works
"""

import os
import sys
import django
from decimal import Decimal
from datetime import date, timedelta

# Setup Django
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

try:
    from dotenv import load_dotenv
    load_dotenv()
except ImportError:
    pass

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

from loans.models import Loan, LoanApplication, LoanProduct, RolloverRequest
from users.models import CustomUser
from django.utils import timezone

def setup_test_data():
    """Create test loan and rollover request"""
    print("🔧 Setting up test data...")
    print("-" * 60)
    
    # Get or create test borrower
    try:
        borrower = CustomUser.objects.filter(role='borrower').first()
        if not borrower:
            print("⚠️  No borrowers found. Creating test borrower...")
            borrower = CustomUser.objects.create_user(
                username='test_borrower_rollover',
                email='test@rollover.com',
                password='test123',
                first_name='Test',
                last_name='Borrower',
                role='borrower',
                phone_number='0712345678'
            )
            print(f"✅ Created test borrower: {borrower.username}")
        else:
            print(f"✅ Using existing borrower: {borrower.get_full_name()}")
    except Exception as e:
        print(f"❌ Error getting borrower: {e}")
        return None, None, None
    
    # Get loan product
    try:
        loan_product = LoanProduct.objects.first()
        if not loan_product:
            print("❌ No loan products found. Please create one first.")
            return None, None, None
        print(f"✅ Using loan product: {loan_product.name}")
    except Exception as e:
        print(f"❌ Error getting loan product: {e}")
        return None, None, None
    
    # Create test loan application
    try:
        application = LoanApplication.objects.create(
            borrower=borrower,
            loan_product=loan_product,
            requested_amount=Decimal('50000.00'),
            requested_duration=30,
            purpose='Test loan for rollover testing',
            status='approved',
            interest_amount=Decimal('5000.00'),
            processing_fee_amount=Decimal('2500.00'),
            total_amount=Decimal('57500.00')
        )
        print(f"✅ Created loan application: {application.id}")
    except Exception as e:
        print(f"❌ Error creating application: {e}")
        return None, None, None
    
    # Create test loan
    try:
        import uuid
        loan_number = f"{date.today().strftime('%d%m%Y')}-TEST{str(uuid.uuid4())[:6].upper()}"
        loan = Loan.objects.create(
            application=application,
            borrower=borrower,
            loan_number=loan_number,
            principal_amount=Decimal('50000.00'),
            interest_amount=Decimal('5000.00'),
            processing_fee=Decimal('2500.00'),
            total_amount=Decimal('57500.00'),
            disbursement_date=timezone.now() - timedelta(days=20),
            due_date=timezone.now() + timedelta(days=10),
            duration_days=30,
            status='active'
        )
        print(f"✅ Created test loan: {loan.loan_number}")
        print(f"   Principal: KES {loan.principal_amount:,.2f}")
        print(f"   Interest: KES {loan.interest_amount:,.2f}")
        print(f"   Total: KES {loan.total_amount:,.2f}")
    except Exception as e:
        print(f"❌ Error creating loan: {e}")
        return None, None, None
    
    # Create rollover request
    try:
        # Calculate rollover fee
        rollover_fee_pct = loan_product.rollover_fee_percentage or Decimal('0')
        rollover_fee = (loan.principal_amount * rollover_fee_pct) / Decimal('100')
        
        rollover = RolloverRequest.objects.create(
            loan=loan,
            borrower=borrower,
            requested_amount=Decimal('75000.00'),  # Increased amount
            requested_duration=60,  # Extended duration
            requested_interest_rate=Decimal('8000.00'),  # Custom interest amount
            requested_processing_fee=Decimal('3500.00'),  # Custom processing fee
            reason='Test rollover - extending loan term and increasing amount',
            rollover_fee=rollover_fee,
            status='pending'
        )
        print(f"✅ Created rollover request: {rollover.id}")
        print(f"   Requested Amount: KES {rollover.requested_amount:,.2f}")
        print(f"   Requested Duration: {rollover.requested_duration} days")
        print(f"   Custom Interest: KES {rollover.requested_interest_rate:,.2f}")
        print(f"   Rollover Fee: KES {rollover.rollover_fee:,.2f}")
    except Exception as e:
        print(f"❌ Error creating rollover: {e}")
        return None, None, None
    
    return loan, rollover, borrower

def test_rollover_approval(loan, rollover, borrower):
    """Test the rollover approval process"""
    print("\n🧪 Testing Rollover Approval")
    print("=" * 60)
    
    # Capture original loan data
    original_loan_id = loan.id
    original_loan_number = loan.loan_number
    original_principal = loan.principal_amount
    original_interest = loan.interest_amount
    original_total = loan.total_amount
    original_duration = loan.duration_days
    original_due_date = loan.due_date
    
    print(f"\n📋 BEFORE Rollover:")
    print(f"   Loan ID: {original_loan_id}")
    print(f"   Loan Number: {original_loan_number}")
    print(f"   Principal: KES {original_principal:,.2f}")
    print(f"   Interest: KES {original_interest:,.2f}")
    print(f"   Total: KES {original_total:,.2f}")
    print(f"   Duration: {original_duration} days")
    print(f"   Due Date: {original_due_date}")
    print(f"   is_rolled_over: {loan.is_rolled_over}")
    
    # Get or create admin user for approval
    try:
        admin = CustomUser.objects.filter(is_staff=True).first()
        if not admin:
            admin = borrower  # Use borrower if no admin
        print(f"\n👤 Approver: {admin.username}")
    except Exception as e:
        print(f"❌ Error getting admin: {e}")
        return False
    
    # Approve the rollover
    print(f"\n🔄 Approving rollover...")
    try:
        updated_loan = rollover.approve(
            approved_by=admin,
            notes="Test approval - verifying update logic"
        )
        print("✅ Rollover approved successfully!")
    except Exception as e:
        print(f"❌ ERROR during approval: {e}")
        import traceback
        traceback.print_exc()
        return False
    
    # Verify the results
    print(f"\n📋 AFTER Rollover:")
    print(f"   Loan ID: {updated_loan.id}")
    print(f"   Loan Number: {updated_loan.loan_number}")
    print(f"   Principal: KES {updated_loan.principal_amount:,.2f}")
    print(f"   Interest: KES {updated_loan.interest_amount:,.2f}")
    print(f"   Total: KES {updated_loan.total_amount:,.2f}")
    print(f"   Duration: {updated_loan.duration_days} days")
    print(f"   Due Date: {updated_loan.due_date}")
    print(f"   is_rolled_over: {updated_loan.is_rolled_over}")
    
    # Verify it's the SAME loan (not a new one)
    print(f"\n✅ Verification:")
    if updated_loan.id == original_loan_id:
        print(f"   ✅ Same loan ID: {updated_loan.id} == {original_loan_id}")
    else:
        print(f"   ❌ Different loan ID: {updated_loan.id} != {original_loan_id}")
        return False
    
    if updated_loan.loan_number == original_loan_number:
        print(f"   ✅ Same loan number: {updated_loan.loan_number}")
    else:
        print(f"   ❌ Different loan number: {updated_loan.loan_number} != {original_loan_number}")
        return False
    
    if updated_loan.principal_amount == rollover.requested_amount:
        print(f"   ✅ Principal updated to: KES {updated_loan.principal_amount:,.2f}")
    else:
        print(f"   ❌ Principal not updated correctly")
        return False
    
    if updated_loan.interest_amount == rollover.requested_interest_rate:
        print(f"   ✅ Interest updated to: KES {updated_loan.interest_amount:,.2f}")
    else:
        print(f"   ❌ Interest not updated correctly")
        return False
    
    if updated_loan.duration_days == rollover.requested_duration:
        print(f"   ✅ Duration updated to: {updated_loan.duration_days} days")
    else:
        print(f"   ❌ Duration not updated correctly")
        return False
    
    if updated_loan.is_rolled_over:
        print(f"   ✅ is_rolled_over flag set to True")
    else:
        print(f"   ❌ is_rolled_over flag not set")
        return False
    
    # Check for duplicate loan numbers in database
    print(f"\n🔍 Checking for duplicate loan numbers...")
    duplicate_count = Loan.objects.filter(loan_number=original_loan_number).count()
    if duplicate_count == 1:
        print(f"   ✅ Only one loan with number {original_loan_number}")
    else:
        print(f"   ❌ Found {duplicate_count} loans with number {original_loan_number}!")
        return False
    
    return True

def cleanup_test_data(loan, rollover):
    """Clean up test data"""
    print(f"\n🧹 Cleaning up test data...")
    try:
        if rollover:
            rollover.delete()
            print("   ✅ Deleted rollover request")
        if loan:
            loan.application.delete()  # Will cascade delete loan
            print("   ✅ Deleted loan and application")
    except Exception as e:
        print(f"   ⚠️  Cleanup warning: {e}")

def main():
    print("=" * 60)
    print("🚀 Testing Rollover Update Logic")
    print("=" * 60)
    
    # Setup test data
    loan, rollover, borrower = setup_test_data()
    
    if not loan or not rollover:
        print("\n❌ Failed to setup test data")
        return False
    
    # Test rollover approval
    success = test_rollover_approval(loan, rollover, borrower)
    
    # Cleanup
    print("\n🧹 Cleaning up test data...")
    cleanup_test_data(loan, rollover)
    
    # Summary
    print("\n" + "=" * 60)
    if success:
        print("✅ ALL TESTS PASSED!")
        print("\nThe rollover update logic works correctly:")
        print("  ✅ Updates existing loan (doesn't create new one)")
        print("  ✅ No duplicate loan numbers")
        print("  ✅ All fields updated correctly")
        print("  ✅ is_rolled_over flag set properly")
        print("\n🎉 Ready for production deployment!")
    else:
        print("❌ TESTS FAILED!")
        print("\nPlease review the errors above.")
    print("=" * 60)
    
    return success

if __name__ == '__main__':
    try:
        success = main()
        sys.exit(0 if success else 1)
    except KeyboardInterrupt:
        print("\n\n⚠️  Test interrupted by user")
        sys.exit(1)
    except Exception as e:
        print(f"\n\n❌ Unexpected error: {e}")
        import traceback
        traceback.print_exc()
        sys.exit(1)
