#!/usr/bin/env python3
"""
Configuration finale et complète de Keycloak pour UnionFlow
Approche step-by-step avec vérifications à chaque étape
"""

import requests
import json
import time

class FinalSetup:
    def __init__(self, base_url: str = "http://localhost:8180"):
        self.base_url = base_url
        self.session = requests.Session()
        self.admin_token = None
        
    def get_admin_token(self) -> bool:
        """Obtient le token admin"""
        credentials = [("admin", "admin"), ("admin", "admin123")]
        
        for username, password in credentials:
            try:
                data = {
                    "username": username,
                    "password": password,
                    "grant_type": "password",
                    "client_id": "admin-cli"
                }
                
                response = self.session.post(
                    f"{self.base_url}/realms/master/protocol/openid-connect/token",
                    data=data,
                    headers={"Content-Type": "application/x-www-form-urlencoded"}
                )
                
                if response.status_code == 200:
                    token_data = response.json()
                    self.admin_token = token_data.get("access_token")
                    if self.admin_token:
                        print(f"✅ Token obtenu avec {username}/{password}")
                        return True
                        
            except Exception as e:
                continue
                
        return False
    
    def create_simple_user(self, realm_name: str, username: str, password: str) -> bool:
        """Crée un utilisateur de manière simple"""
        print(f"👤 Création de {username}...")
        
        # 1. Créer l'utilisateur avec le minimum requis
        user_data = {
            "username": username,
            "enabled": True,
            "credentials": [{
                "type": "password",
                "value": password,
                "temporary": False
            }]
        }
        
        try:
            # Supprimer s'il existe
            existing_response = self.session.get(
                f"{self.base_url}/admin/realms/{realm_name}/users?username={username}",
                headers={"Authorization": f"Bearer {self.admin_token}"}
            )
            
            if existing_response.status_code == 200:
                existing_users = existing_response.json()
                for user in existing_users:
                    if user.get("username") == username:
                        user_id = user.get("id")
                        self.session.delete(
                            f"{self.base_url}/admin/realms/{realm_name}/users/{user_id}",
                            headers={"Authorization": f"Bearer {self.admin_token}"}
                        )
                        print(f"   ✓ Utilisateur existant supprimé")
                        break
            
            # Créer le nouvel utilisateur
            response = self.session.post(
                f"{self.base_url}/admin/realms/{realm_name}/users",
                json=user_data,
                headers={
                    "Authorization": f"Bearer {self.admin_token}",
                    "Content-Type": "application/json"
                }
            )
            
            if response.status_code == 201:
                print(f"   ✓ Utilisateur créé")
                
                # Test immédiat
                time.sleep(1)
                test_result = self.test_user_auth(realm_name, username, password)
                if test_result:
                    print(f"   ✅ {username} fonctionne !")
                    return True
                else:
                    print(f"   ❌ {username} ne fonctionne pas")
                    return False
            else:
                print(f"   ❌ Erreur création: {response.status_code}")
                return False
                
        except Exception as e:
            print(f"   ❌ Exception: {e}")
            return False
    
    def test_user_auth(self, realm_name: str, username: str, password: str) -> bool:
        """Teste l'authentification d'un utilisateur"""
        try:
            data = {
                "username": username,
                "password": password,
                "grant_type": "password",
                "client_id": "unionflow-mobile"
            }
            
            response = self.session.post(
                f"{self.base_url}/realms/{realm_name}/protocol/openid-connect/token",
                data=data,
                headers={"Content-Type": "application/x-www-form-urlencoded"}
            )
            
            return response.status_code == 200 and "access_token" in response.json()
            
        except:
            return False
    
    def setup_minimal(self):
        """Configuration minimale qui fonctionne"""
        print("=" * 80)
        print("🚀 CONFIGURATION MINIMALE UNIONFLOW")
        print("=" * 80)
        print()
        
        # 1. Token admin
        if not self.get_admin_token():
            print("❌ Impossible d'obtenir le token admin")
            return False
        
        # 2. Vérifier que le realm existe
        realm_name = "unionflow"
        try:
            response = self.session.get(
                f"{self.base_url}/admin/realms/{realm_name}",
                headers={"Authorization": f"Bearer {self.admin_token}"}
            )
            if response.status_code == 200:
                print(f"✅ Realm {realm_name} existe")
            else:
                print(f"❌ Realm {realm_name} n'existe pas")
                return False
        except:
            print(f"❌ Erreur vérification realm")
            return False
        
        # 3. Vérifier que le client existe
        client_id = "unionflow-mobile"
        try:
            clients_response = self.session.get(
                f"{self.base_url}/admin/realms/{realm_name}/clients",
                headers={"Authorization": f"Bearer {self.admin_token}"}
            )
            
            client_exists = False
            if clients_response.status_code == 200:
                clients = clients_response.json()
                for client in clients:
                    if client.get("clientId") == client_id:
                        client_exists = True
                        break
            
            if client_exists:
                print(f"✅ Client {client_id} existe")
            else:
                print(f"❌ Client {client_id} n'existe pas")
                return False
                
        except:
            print(f"❌ Erreur vérification client")
            return False
        
        print()
        
        # 4. Créer les utilisateurs un par un avec test immédiat
        users = [
            ("marie.active", "Marie123!"),
            ("superadmin", "SuperAdmin123!"),
            ("jean.simple", "Jean123!")
        ]
        
        success_count = 0
        for username, password in users:
            if self.create_simple_user(realm_name, username, password):
                success_count += 1
            print()
        
        print("=" * 80)
        print(f"📊 RÉSULTAT: {success_count}/{len(users)} comptes fonctionnent")
        print("=" * 80)
        
        if success_count > 0:
            print()
            print("🎉 AU MOINS UN COMPTE FONCTIONNE !")
            print()
            print("🚀 COMPTES OPÉRATIONNELS :")
            for username, password in users:
                if self.test_user_auth(realm_name, username, password):
                    print(f"   ✅ {username} / {password}")
                else:
                    print(f"   ❌ {username} / {password}")
            
            print()
            print("📱 TESTEZ MAINTENANT SUR VOTRE APPLICATION MOBILE !")
            print("   Utilisez un des comptes qui fonctionne")
            
            return True
        else:
            print("❌ Aucun compte ne fonctionne")
            print()
            print("🔧 SOLUTION MANUELLE :")
            print("1. Ouvrez http://localhost:8180/admin/")
            print("2. Connectez-vous comme admin")
            print("3. Allez dans le realm 'unionflow'")
            print("4. Créez manuellement l'utilisateur 'marie.active'")
            print("5. Définissez le mot de passe 'Marie123!' (non temporaire)")
            print("6. Testez avec votre application mobile")
            
            return False


def main():
    setup = FinalSetup()
    setup.setup_minimal()


if __name__ == "__main__":
    main()
