#!/usr/bin/env python3
"""
Test final avec diagnostic complet
"""

import requests
import json

def final_diagnostic():
    base_url = "http://localhost:8180"
    session = requests.Session()
    
    print("=" * 80)
    print("🔍 DIAGNOSTIC FINAL KEYCLOAK UNIONFLOW")
    print("=" * 80)
    print()
    
    # 1. Test de base
    try:
        response = session.get(f"{base_url}", timeout=5)
        print(f"✅ Keycloak accessible (Status: {response.status_code})")
    except:
        print("❌ Keycloak non accessible")
        return
    
    # 2. Test du realm
    try:
        response = session.get(f"{base_url}/realms/unionflow")
        if response.status_code == 200:
            print("✅ Realm unionflow accessible")
        else:
            print(f"❌ Realm unionflow non accessible: {response.status_code}")
            return
    except:
        print("❌ Erreur accès realm")
        return
    
    # 3. Test d'authentification détaillé
    print()
    print("🧪 Test d'authentification détaillé...")
    
    test_data = {
        "username": "marie.active",
        "password": "Marie123!",
        "grant_type": "password",
        "client_id": "unionflow-mobile"
    }
    
    print(f"Données envoyées: {test_data}")
    print(f"URL: {base_url}/realms/unionflow/protocol/openid-connect/token")
    
    try:
        response = session.post(
            f"{base_url}/realms/unionflow/protocol/openid-connect/token",
            data=test_data,
            headers={"Content-Type": "application/x-www-form-urlencoded"}
        )
        
        print(f"Status: {response.status_code}")
        print(f"Headers: {dict(response.headers)}")
        print(f"Response: {response.text}")
        
        if response.status_code == 200:
            token_data = response.json()
            if "access_token" in token_data:
                print("✅ AUTHENTIFICATION RÉUSSIE !")
                print(f"Token reçu (longueur: {len(token_data['access_token'])})")
            else:
                print("❌ Token manquant dans la réponse")
        else:
            print("❌ Authentification échouée")
            
    except Exception as e:
        print(f"❌ Exception: {e}")
    
    print()
    
    # 4. Test avec différents clients
    print("🧪 Test avec différents clients...")
    
    clients_to_test = ["unionflow-mobile", "account", "admin-cli"]
    
    for client_id in clients_to_test:
        test_data_client = {
            "username": "marie.active",
            "password": "Marie123!",
            "grant_type": "password",
            "client_id": client_id
        }
        
        try:
            response = session.post(
                f"{base_url}/realms/unionflow/protocol/openid-connect/token",
                data=test_data_client,
                headers={"Content-Type": "application/x-www-form-urlencoded"}
            )
            
            if response.status_code == 200:
                print(f"   ✅ {client_id}: FONCTIONNE")
            else:
                print(f"   ❌ {client_id}: {response.status_code}")
                
        except:
            print(f"   ❌ {client_id}: Exception")
    
    print()
    
    # 5. Vérification de la configuration du client via admin API
    print("🔍 Vérification de la configuration du client...")
    
    # Obtenir token admin
    admin_data = {
        "username": "admin",
        "password": "admin",
        "grant_type": "password",
        "client_id": "admin-cli"
    }
    
    try:
        admin_response = session.post(
            f"{base_url}/realms/master/protocol/openid-connect/token",
            data=admin_data,
            headers={"Content-Type": "application/x-www-form-urlencoded"}
        )
        
        if admin_response.status_code == 200:
            admin_token = admin_response.json().get("access_token")
            
            # Récupérer la config du client
            clients_response = session.get(
                f"{base_url}/admin/realms/unionflow/clients",
                headers={"Authorization": f"Bearer {admin_token}"}
            )
            
            if clients_response.status_code == 200:
                clients = clients_response.json()
                for client in clients:
                    if client.get("clientId") == "unionflow-mobile":
                        print("   ✅ Client unionflow-mobile trouvé:")
                        print(f"      - Enabled: {client.get('enabled')}")
                        print(f"      - Public: {client.get('publicClient')}")
                        print(f"      - Direct Access: {client.get('directAccessGrantsEnabled')}")
                        print(f"      - Standard Flow: {client.get('standardFlowEnabled')}")
                        break
                else:
                    print("   ❌ Client unionflow-mobile non trouvé")
            else:
                print(f"   ❌ Erreur récupération clients: {clients_response.status_code}")
        else:
            print("   ❌ Impossible d'obtenir le token admin")
            
    except Exception as e:
        print(f"   ❌ Exception vérification client: {e}")
    
    print()
    print("=" * 80)
    print("🎯 RÉSUMÉ DU DIAGNOSTIC")
    print("=" * 80)
    print()
    print("Si l'authentification ne fonctionne toujours pas,")
    print("la solution la plus simple est la configuration manuelle :")
    print()
    print("1. Ouvrez http://localhost:8180/admin/")
    print("2. Connectez-vous avec admin/admin")
    print("3. Sélectionnez le realm 'unionflow'")
    print("4. Allez dans Users > marie.active")
    print("5. Onglet Credentials > Set password")
    print("6. Entrez 'Marie123!' et décochez 'Temporary'")
    print("7. Testez avec votre application mobile")
    print()
    print("🚀 Une fois qu'un compte fonctionne, votre app mobile")
    print("   pourra s'authentifier avec Keycloak !")

if __name__ == "__main__":
    final_diagnostic()
