#!/usr/bin/env python3
"""
Test script to verify the rollover interest amount change works correctly
Run this after deployment to verify everything is working
"""

import os
import sys
import django
from decimal import Decimal

# 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 RolloverRequest, Loan, LoanApplication
from django.contrib.auth import get_user_model

User = get_user_model()

def test_field_size():
    """Test that the database field can accept large amounts"""
    print("🧪 Test 1: Database Field Size")
    print("-" * 50)
    
    try:
        # Try to get the field max_digits
        field = RolloverRequest._meta.get_field('requested_interest_rate')
        print(f"Field type: {field.__class__.__name__}")
        print(f"Max digits: {field.max_digits}")
        print(f"Decimal places: {field.decimal_places}")
        print(f"Help text: {field.help_text}")
        
        if field.max_digits == 12 and field.decimal_places == 2:
            print("✅ Field is correctly configured as DECIMAL(12,2)")
            return True
        else:
            print(f"❌ Field is DECIMAL({field.max_digits},{field.decimal_places}) - expected DECIMAL(12,2)")
            return False
    except Exception as e:
        print(f"❌ Error checking field: {str(e)}")
        return False

def test_calculation_logic():
    """Test that the calculation uses amount directly"""
    print("\n🧪 Test 2: Interest Calculation Logic")
    print("-" * 50)
    
    # Check the approve method source code
    import inspect
    approve_method = RolloverRequest.approve
    source = inspect.getsource(approve_method)
    
    # Check for the new calculation pattern
    if "interest_amount = new_interest_rate" in source and "# new_interest_rate is now the actual interest amount" in source:
        print("✅ Approve method uses direct amount (not percentage calculation)")
        return True
    elif "new_interest_rate / Decimal('100')" in source:
        print("❌ Approve method still using percentage calculation!")
        print("   Expected: interest_amount = new_interest_rate")
        print("   Found: percentage-based calculation")
        return False
    else:
        print("⚠️  Could not verify calculation logic from source")
        return None

def test_with_sample_data():
    """Test with sample calculation"""
    print("\n🧪 Test 3: Sample Calculation")
    print("-" * 50)
    
    # Test values
    principal = Decimal('100000.00')
    custom_interest = Decimal('5000.00')
    
    print(f"Principal: KES {principal:,.2f}")
    print(f"Custom Interest (as amount): KES {custom_interest:,.2f}")
    
    # The new logic should use the custom_interest directly
    expected_interest = custom_interest
    
    print(f"Expected interest amount: KES {expected_interest:,.2f}")
    print("✅ Calculation logic: Direct amount usage")
    
    return True

def test_existing_rollovers():
    """Check existing rollover requests"""
    print("\n🧪 Test 4: Existing Rollover Requests")
    print("-" * 50)
    
    try:
        pending = RolloverRequest.objects.filter(status='pending')
        pending_count = pending.count()
        
        print(f"Total pending rollovers: {pending_count}")
        
        if pending_count > 0:
            print("\n⚠️  Pending rollovers found:")
            for rollover in pending[:5]:  # Show first 5
                print(f"\n  Loan: {rollover.loan.loan_number}")
                print(f"  Requested Amount: KES {rollover.requested_amount:,.2f}")
                print(f"  Custom Interest: {rollover.requested_interest_rate if rollover.requested_interest_rate else 'Default'}")
                if rollover.requested_interest_rate:
                    print(f"  ⚠️  This will be treated as KES {rollover.requested_interest_rate:,.2f} (not {rollover.requested_interest_rate}%)")
        else:
            print("✅ No pending rollovers to worry about")
        
        return True
    except Exception as e:
        print(f"❌ Error checking rollovers: {str(e)}")
        return False

def test_form_validation():
    """Check that validation accepts large amounts"""
    print("\n🧪 Test 5: Validation Logic")
    print("-" * 50)
    
    # Check the validation in views.py
    try:
        from loans import views
        import inspect
        
        source = inspect.getsource(views.request_rollover)
        
        # Check for old percentage validation (should be removed)
        if "interest_rate >= 1000" in source or "max is 999.99" in source:
            print("❌ Old percentage validation still present (max 999.99)")
            return False
        
        # Check for new amount validation
        if "interest_rate < 0" in source and "cannot be negative" in source:
            print("✅ Validation accepts any positive amount (no max limit)")
            return True
        else:
            print("⚠️  Could not verify validation logic")
            return None
    except Exception as e:
        print(f"❌ Error checking validation: {str(e)}")
        return False

def main():
    print("=" * 60)
    print("🚀 Testing Rollover Interest Amount Change")
    print("=" * 60)
    
    results = []
    
    # Run all tests
    results.append(("Field Size", test_field_size()))
    results.append(("Calculation Logic", test_calculation_logic()))
    results.append(("Sample Calculation", test_with_sample_data()))
    results.append(("Existing Rollovers", test_existing_rollovers()))
    results.append(("Form Validation", test_form_validation()))
    
    # Summary
    print("\n" + "=" * 60)
    print("📊 Test Summary")
    print("=" * 60)
    
    passed = sum(1 for _, result in results if result is True)
    failed = sum(1 for _, result in results if result is False)
    skipped = sum(1 for _, result in results if result is None)
    
    for test_name, result in results:
        if result is True:
            print(f"✅ {test_name}: PASSED")
        elif result is False:
            print(f"❌ {test_name}: FAILED")
        else:
            print(f"⚠️  {test_name}: SKIPPED")
    
    print(f"\nTotal: {passed} passed, {failed} failed, {skipped} skipped")
    
    if failed == 0:
        print("\n🎉 All tests passed! The change is working correctly.")
        print("\nNext steps:")
        print("  1. Test the rollover form in the web interface")
        print("  2. Create a test rollover with custom interest amount")
        print("  3. Approve it and verify the loan has correct interest")
        return True
    else:
        print("\n⚠️  Some tests failed. Please review the changes.")
        return False

if __name__ == '__main__':
    try:
        success = main()
        sys.exit(0 if success else 1)
    except Exception as e:
        print(f"\n❌ Test suite error: {str(e)}")
        import traceback
        traceback.print_exc()
        sys.exit(1)
