#!/usr/bin/env python
"""List all users in the Haven Grazuri system"""
import os
import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from users.models import CustomUser

print("\n" + "=" * 100)
print("HAVEN GRAZURI INVESTMENT LIMITED - ALL SYSTEM USERS")
print("=" * 100)

all_users = CustomUser.objects.all().order_by('role', 'username')
print(f"\nTotal Users: {all_users.count()}\n")

# Group by role
roles = {}
for user in all_users:
    if user.role not in roles:
        roles[user.role] = []
    roles[user.role].append(user)

# Display by role
for role, users in sorted(roles.items()):
    role_display = role.replace('_', ' ').title()
    print(f"\n{'=' * 100}")
    print(f"{role_display.upper()} ({len(users)} users)")
    print('=' * 100)
    
    for user in users:
        print(f"\n  Username: {user.username}")
        print(f"  Name: {user.first_name} {user.last_name}")
        print(f"  Email: {user.email}")
        print(f"  Phone: {user.phone_number}")
        print(f"  Branch: {user.branch.name if user.branch else 'None'}")
        print(f"  Status: {user.status}")
        print(f"  Active: {'✓' if user.is_active else '✗'}")
        
        if user.is_staff:
            branches = user.accessible_branches.all()
            if branches:
                print(f"  Accessible Branches: {', '.join([b.name for b in branches])}")

print("\n" + "=" * 100)
print("SUMMARY BY ROLE")
print("=" * 100)
for role, users in sorted(roles.items()):
    role_display = role.replace('_', ' ').title()
    print(f"  {role_display}: {len(users)} users")

print("\n" + "=" * 100)
print("IMPORTED GRAZURI USERS")
print("=" * 100)
grazuri_users = ['gladys', 'jmwangi', 'andmin', 'gts']
for username in grazuri_users:
    try:
        user = CustomUser.objects.get(username=username)
        print(f"  ✓ {user.username} - {user.first_name} {user.last_name} ({user.role})")
    except:
        print(f"  ✗ {username} - NOT FOUND")

print("\n" + "=" * 100)
