"""
Test script to verify URL routing for simplified permissions
"""
import os
import sys
import django

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from django.urls import reverse, resolve
from django.test import RequestFactory
from django.contrib.auth import get_user_model
from users.models import CustomUser
import uuid

User = get_user_model()

def test_url_generation():
    """Test that the URL is generated correctly"""
    print("Testing URL generation...")
    
    # Get a test user
    test_user = CustomUser.objects.filter(is_staff=True).first()
    if not test_user:
        print("No staff users found. Creating test user...")
        test_user = CustomUser.objects.create_user(
            username='test_staff',
            email='test@test.com',
            phone_number='+254700000999',
            password='test123',
            role='loan_officer',
            is_staff=True
        )
    
    try:
        url = reverse('users:simplified_user_permissions', args=[str(test_user.id)])
        print(f"[OK] URL generated: {url}")
        print(f"  Expected: /simplified-permissions/{test_user.id}/")
        
        # Test URL resolution
        resolved = resolve(url)
        print(f"[OK] URL resolves to view: {resolved.func.__name__}")
        print(f"  View module: {resolved.func.__module__}")
        
        # Check if it matches the correct view
        from users.simplified_permissions_views import simplified_user_permissions
        if resolved.func == simplified_user_permissions:
            print("[OK] URL correctly resolves to simplified_user_permissions view")
        else:
            print(f"[ERROR] URL resolves to wrong view: {resolved.func.__name__}")
            print(f"  Expected: simplified_user_permissions")
        
        return True
    except Exception as e:
        print(f"[ERROR] Error generating URL: {e}")
        import traceback
        traceback.print_exc()
        return False

def test_url_patterns():
    """Check for conflicting URL patterns"""
    print("\nChecking for URL pattern conflicts...")
    
    from django.urls import get_resolver
    from django.conf import settings
    
    resolver = get_resolver()
    
    # Find all patterns that might match
    patterns_to_check = [
        'simplified-permissions',
        'admins',
        'permissions',
    ]
    
    for pattern in patterns_to_check:
        print(f"\nPatterns containing '{pattern}':")
        for url_pattern in resolver.url_patterns:
            if hasattr(url_pattern, 'pattern'):
                pattern_str = str(url_pattern.pattern)
                if pattern in pattern_str.lower():
                    print(f"  - {pattern_str} -> {url_pattern.name if hasattr(url_pattern, 'name') else 'N/A'}")

def test_view_access():
    """Test that the view doesn't log in as the target user"""
    print("\nTesting view access...")
    
    # Get admin user
    admin = CustomUser.objects.filter(role='admin', is_staff=True).first()
    if not admin:
        print("No admin user found. Please create one first.")
        return False
    
    # Get target user
    target_user = CustomUser.objects.filter(is_staff=True).exclude(id=admin.id).first()
    if not target_user:
        print("No target user found. Please create one first.")
        return False
    
    print(f"Admin: {admin.username} (ID: {admin.id})")
    print(f"Target: {target_user.username} (ID: {target_user.id})")
    
    # Create a request
    factory = RequestFactory()
    url = reverse('users:simplified_user_permissions', args=[str(target_user.id)])
    request = factory.get(url)
    request.user = admin
    
    # Import the view
    from users.simplified_permissions_views import simplified_user_permissions
    
    try:
        # Call the view
        response = simplified_user_permissions(request, str(target_user.id))
        
        # Check that admin is still logged in
        if hasattr(response, 'status_code'):
            if response.status_code == 200:
                print("[OK] View returns 200 OK")
                print("[OK] Admin should still be logged in (check manually)")
            elif response.status_code == 302:
                print(f"[OK] View redirects (status: {response.status_code})")
                print(f"  Redirect location: {response.url if hasattr(response, 'url') else 'N/A'}")
            else:
                print(f"[WARN] View returns status: {response.status_code}")
        else:
            print("[OK] View executed without error")
        
        return True
    except Exception as e:
        print(f"✗ Error calling view: {e}")
        import traceback
        traceback.print_exc()
        return False

if __name__ == '__main__':
    print("=" * 80)
    print("URL ROUTING TEST")
    print("=" * 80)
    
    test_url_generation()
    test_url_patterns()
    test_view_access()
    
    print("\n" + "=" * 80)
    print("TEST COMPLETE")
    print("=" * 80)

