"""
刪除 Keycloak 用戶
"""
import sys
sys.path.insert(0, '.')

from app.services.keycloak_service import KeycloakService

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

if len(sys.argv) < 2:
    print("Usage: python delete_keycloak_user.py <user_id_or_username>")
    sys.exit(1)

user_identifier = sys.argv[1]

print(f"=== Deleting Keycloak User ===\n")
print(f"Identifier: {user_identifier}\n")

try:
    # 檢查是否為 UUID (user_id) 或 username
    if '-' in user_identifier and len(user_identifier) == 36:
        # 是 UUID,直接刪除
        user_id = user_identifier
    else:
        # 是 username,先查詢 user_id
        user = keycloak.get_user_by_username(user_identifier)
        if not user:
            print(f"ERROR: User '{user_identifier}' not found")
            sys.exit(1)
        user_id = user['id']
        print(f"Found user: {user['username']} (Email: {user['email']})")
        print(f"User ID: {user_id}\n")

    # 刪除用戶
    success = keycloak.delete_user(user_id)

    if success:
        print("\nSUCCESS: User deleted successfully")
    else:
        print("\nERROR: Failed to delete user")
        sys.exit(1)

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