#!/usr/bin/env python3
"""
Script de debug pour voir les erreurs exactes
"""

import requests
import json

def debug_user_creation():
    base_url = "http://localhost:8180"
    session = requests.Session()
    
    # Obtenir token admin
    data = {
        "username": "admin",
        "password": "admin",
        "grant_type": "password",
        "client_id": "admin-cli"
    }
    
    response = session.post(
        f"{base_url}/realms/master/protocol/openid-connect/token",
        data=data,
        headers={"Content-Type": "application/x-www-form-urlencoded"}
    )
    
    if response.status_code != 200:
        print("❌ Impossible d'obtenir le token admin")
        return
    
    admin_token = response.json().get("access_token")
    print("✅ Token admin obtenu")
    
    # Essayer de créer un utilisateur simple
    user_data = {
        "username": "test.user",
        "enabled": True,
        "credentials": [{
            "type": "password",
            "value": "Test123!",
            "temporary": False
        }]
    }
    
    print("🧪 Test création utilisateur...")
    print(f"Données envoyées: {json.dumps(user_data, indent=2)}")
    
    response = session.post(
        f"{base_url}/admin/realms/unionflow/users",
        json=user_data,
        headers={
            "Authorization": f"Bearer {admin_token}",
            "Content-Type": "application/json"
        }
    )
    
    print(f"Status: {response.status_code}")
    print(f"Headers: {dict(response.headers)}")
    print(f"Response: {response.text}")
    
    if response.status_code == 201:
        print("✅ Utilisateur créé avec succès")
        
        # Test d'authentification
        auth_data = {
            "username": "test.user",
            "password": "Test123!",
            "grant_type": "password",
            "client_id": "unionflow-mobile"
        }
        
        auth_response = session.post(
            f"{base_url}/realms/unionflow/protocol/openid-connect/token",
            data=auth_data,
            headers={"Content-Type": "application/x-www-form-urlencoded"}
        )
        
        print(f"Auth Status: {auth_response.status_code}")
        print(f"Auth Response: {auth_response.text}")
        
    else:
        print("❌ Erreur création utilisateur")
        try:
            error_data = response.json()
            print(f"Erreur détaillée: {json.dumps(error_data, indent=2)}")
        except:
            print("Pas de JSON dans la réponse d'erreur")

if __name__ == "__main__":
    debug_user_creation()
