import os
import django
from decimal import Decimal

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from django.test import Client
from users.models import CustomUser
from loans.models import LoanProduct

# Get a borrower and loan product
borrower = CustomUser.objects.filter(role='borrower', username__startswith='borrower').first()
loan_product = LoanProduct.objects.filter(is_active=True).first()

if not borrower:
    print("❌ No borrower found. Please create borrowers first.")
    exit(1)

if not loan_product:
    print("❌ No loan product found. Please create loan products first.")
    exit(1)

print(f"Testing loan application for:")
print(f"  Borrower: {borrower.get_full_name()} ({borrower.username})")
print(f"  Product: {loan_product.name}")
print(f"  Amount Range: KES {loan_product.min_amount:,.0f} - {loan_product.max_amount:,.0f}")

# Login as borrower
client = Client()
login_response = client.post('/login/', {
    'username': borrower.username,
    'password': 'borrower123'
})

if login_response.status_code != 302:
    print(f"❌ Login failed with status {login_response.status_code}")
    exit(1)

print("✓ Login successful")

# Try to submit a loan application
application_data = {
    'loan_product': str(loan_product.id),
    'amount': str(loan_product.min_amount + 5000),
    'duration_days': loan_product.available_durations[0] if loan_product.available_durations else loan_product.min_duration,
    'repayment_method': loan_product.available_repayment_methods[0] if loan_product.available_repayment_methods else 'monthly',
    'purpose': 'Business expansion and inventory purchase',
}

print(f"\nSubmitting application:")
print(f"  Amount: KES {application_data['amount']}")
print(f"  Duration: {application_data['duration_days']} days")
print(f"  Repayment: {application_data['repayment_method']}")

response = client.post('/loans/new/', application_data)

print(f"\nResponse Status: {response.status_code}")

if response.status_code == 200:
    import json
    try:
        data = json.loads(response.content)
        if data.get('status') == 'success':
            print(f"✓ Application submitted successfully!")
            print(f"  Application ID: {data.get('application_id')}")
            print(f"  Application Number: {data.get('application_number')}")
        else:
            print(f"❌ Application failed: {data.get('message')}")
            if 'errors' in data:
                for field, errors in data['errors'].items():
                    print(f"  {field}: {errors}")
    except json.JSONDecodeError:
        print(f"❌ Invalid JSON response")
        print(response.content.decode()[:500])
elif response.status_code == 302:
    print(f"✓ Redirected to: {response.url}")
else:
    print(f"❌ Unexpected status code")
    print(response.content.decode()[:500])
