"""
檢查 Keycloak 中的現有用戶
"""
import sys
sys.path.insert(0, '.')

from app.services.keycloak_service import KeycloakService

# 初始化 Keycloak 服務
keycloak = KeycloakService()

print("=== Checking Keycloak Users ===\n")

# 檢查是否有用戶
try:
    if keycloak.admin:
        # 取得所有用戶
        users = keycloak.admin.get_users({})
        print(f"Total users in realm 'porscheworld': {len(users)}\n")

        for user in users:
            print(f"Username: {user.get('username')}")
            print(f"  Email: {user.get('email')}")
            print(f"  ID: {user.get('id')}")
            print(f"  Enabled: {user.get('enabled')}")
            print(f"  Email Verified: {user.get('emailVerified')}")
            print()

        # 檢查是否有 porsche.chen 用戶
        target_user = keycloak.get_user_by_username("porsche.chen")
        if target_user:
            print("=== Found 'porsche.chen' user ===")
            print(f"User ID: {target_user.get('id')}")
            print(f"Email: {target_user.get('email')}")
            print(f"\nTo delete this user, run:")
            print(f"  python delete_keycloak_user.py {target_user.get('id')}")
        else:
            print("User 'porsche.chen' not found")

            # 檢查是否有使用 porsche.chen@porscheworld.tw 的用戶
            for user in users:
                if user.get('email') == 'porsche.chen@porscheworld.tw':
                    print(f"\n=== Found user with email 'porsche.chen@porscheworld.tw' ===")
                    print(f"Username: {user.get('username')}")
                    print(f"User ID: {user.get('id')}")
                    print(f"\nTo delete this user, run:")
                    print(f"  python delete_keycloak_user.py {user.get('id')}")
    else:
        print("ERROR: Keycloak Admin not initialized")

except Exception as e:
    print(f"ERROR: {e}")
    import traceback
    traceback.print_exc()
