#!/usr/bin/env python3
"""
Add debug logging to the new_application view to see what's happening
"""

import os

VIEW_FILE = 'loans/views.py'

print("🔍 Adding debug logging to new_application view...")

# Read the file
with open(VIEW_FILE, 'r', encoding='utf-8') as f:
    content = f.read()

# Add logging after the permission check
old_code = '''def new_application(request):
    """Create a new loan application with improved client handling"""
    # Check if user has permission to create loans
    if not request.user.has_permission('loans', 'create'):
        messages.error(request, 'You do not have permission to create loan applications.')
        return redirect('loans:loans')'''

new_code = '''def new_application(request):
    """Create a new loan application with improved client handling"""
    # Check if user has permission to create loans
    print(f"DEBUG new_application: user={request.user.username}, role={request.user.role}, is_staff={request.user.is_staff}")
    has_perm = request.user.has_permission('loans', 'create')
    print(f"DEBUG has_permission('loans', 'create') = {has_perm}")
    
    if not has_perm:
        print(f"DEBUG: Permission DENIED - redirecting to loans:loans")
        messages.error(request, 'You do not have permission to create loan applications.')
        return redirect('loans:loans')
    
    print(f"DEBUG: Permission GRANTED - showing form")'''

if old_code in content:
    content = content.replace(old_code, new_code)
    
    with open(VIEW_FILE, 'w', encoding='utf-8') as f:
        f.write(content)
    
    print("✅ Debug logging added!")
    print("\nRestarting Django...")
    
    os.makedirs('tmp', exist_ok=True)
    with open('tmp/restart.txt', 'a'):
        os.utime('tmp/restart.txt', None)
    
    print("✅ Django restarted!")
    print("\nNow:")
    print("1. Click '+ New Loan Application' button")
    print("2. Check Django logs/console output")
    print("3. You'll see exactly what's happening with permissions")
else:
    print("❌ Code pattern not found - file may have been modified")
