import os
import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from users.models import CustomUser, Branch
from django.db import transaction

def fix_user_branch_assignments():
    """Assign users without branch to the main branch"""
    try:
        with transaction.atomic():
            # Get or create main branch
            main_branch, created = Branch.objects.get_or_create(
                is_main_branch=True,
                defaults={
                    'name': 'Main Branch',
                    'code': 'MAIN',
                    'address': 'Head Office',
                    'phone_number': '+254700000000',
                    'email': 'info@branchbusinessadvance.co.ke',
                    'is_active': True
                }
            )
            
            if created:
                print(f"✅ Created main branch: {main_branch.name}")
            else:
                print(f"✅ Using existing main branch: {main_branch.name}")
            
            # Find users without branch assignment
            users_without_branch = CustomUser.objects.filter(branch__isnull=True)
            count = users_without_branch.count()
            
            if count > 0:
                print(f"Found {count} users without branch assignment:")
                for user in users_without_branch:
                    print(f"  - {user.get_full_name()} ({user.phone_number}) - Role: {user.role}")
                
                # Assign them to main branch
                updated_count = users_without_branch.update(branch=main_branch)
                print(f"✅ Successfully assigned {updated_count} users to {main_branch.name}")
                
                # Verify the test user specifically
                test_user = CustomUser.objects.filter(phone_number='+2540000000565').first()
                if test_user:
                    print(f"✅ Test user '{test_user.get_full_name()}' is now assigned to branch: {test_user.branch.name}")
                else:
                    print("⚠️ Test user with phone +2540000000565 not found")
                    
            else:
                print("✅ All users already have branch assignments")
                
            # Give admin users access to all branches
            admin_users = CustomUser.objects.filter(role='admin')
            all_branches = Branch.objects.filter(is_active=True)
            
            for admin in admin_users:
                admin.accessible_branches.set(all_branches)
                print(f"✅ Gave admin user '{admin.get_full_name()}' access to all branches")
                
            return True
            
    except Exception as e:
        print(f"❌ Error fixing branch assignments: {e}")
        return False

def verify_client_visibility():
    """Verify that clients are now visible in the system"""
    try:
        # Check total borrowers
        total_borrowers = CustomUser.objects.filter(role='borrower').count()
        borrowers_with_branch = CustomUser.objects.filter(role='borrower', branch__isnull=False).count()
        borrowers_without_branch = CustomUser.objects.filter(role='borrower', branch__isnull=True).count()
        
        print(f"\n📊 Client Statistics:")
        print(f"  Total borrowers: {total_borrowers}")
        print(f"  Borrowers with branch: {borrowers_with_branch}")
        print(f"  Borrowers without branch: {borrowers_without_branch}")
        
        # Check the specific test user
        test_user = CustomUser.objects.filter(phone_number='+2540000000565').first()
        if test_user:
            print(f"\n🔍 Test User Details:")
            print(f"  Name: {test_user.get_full_name()}")
            print(f"  Phone: {test_user.phone_number}")
            print(f"  Role: {test_user.role}")
            print(f"  Status: {test_user.status}")
            print(f"  Branch: {test_user.branch.name if test_user.branch else 'No branch assigned'}")
            print(f"  Branch ID: {test_user.branch.id if test_user.branch else 'NULL'}")
        
        return True
        
    except Exception as e:
        print(f"❌ Error verifying client visibility: {e}")
        return False

if __name__ == "__main__":
    print("🔧 Fixing user branch assignments...")
    
    if fix_user_branch_assignments():
        print("\n✅ Branch assignment fix completed successfully!")
        
        print("\n🔍 Verifying client visibility...")
        verify_client_visibility()
        
        print("\n📝 Next Steps:")
        print("1. Go to the client list in your application")
        print("2. Make sure you have the correct branch selected in the branch selector")
        print("3. Your test user should now be visible in the client list")
        print("4. If you still don't see the user, try switching branches or clearing the branch filter")
    else:
        print("❌ Failed to fix branch assignments")