#!/usr/bin/env python3
"""
Configuration Keycloak qui fonctionne - avec email requis
"""

import requests
import json
import time

class WorkingSetup:
    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"""
        try:
            data = {
                "username": "admin",
                "password": "admin",
                "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")
                return self.admin_token is not None
                
        except Exception as e:
            print(f"Erreur obtention token: {e}")
            
        return False
    
    def create_working_user(self, realm_name: str, username: str, email: str, password: str) -> bool:
        """Crée un utilisateur qui fonctionne"""
        print(f"👤 Création de {username}...")
        
        # Supprimer s'il existe
        try:
            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
        except:
            pass
        
        # Créer l'utilisateur avec email
        user_data = {
            "username": username,
            "email": email,
            "enabled": True,
            "emailVerified": True,
            "credentials": [{
                "type": "password",
                "value": password,
                "temporary": False
            }]
        }
        
        try:
            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)
                if self.test_user_auth(realm_name, username, password):
                    print(f"   ✅ {username} FONCTIONNE !")
                    return True
                else:
                    print(f"   ❌ {username} ne fonctionne pas")
                    return False
            else:
                print(f"   ❌ Erreur création: {response.status_code}")
                print(f"       Réponse: {response.text}")
                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_all_users(self):
        """Configure tous les utilisateurs"""
        print("=" * 80)
        print("🚀 CONFIGURATION FINALE UNIONFLOW - AVEC EMAIL")
        print("=" * 80)
        print()
        
        # 1. Token admin
        if not self.get_admin_token():
            print("❌ Impossible d'obtenir le token admin")
            return False
        
        print("✅ Token admin obtenu")
        print()
        
        # 2. Créer tous les utilisateurs
        users = [
            ("marie.active", "marie.active@unionflow.com", "Marie123!"),
            ("superadmin", "superadmin@unionflow.com", "SuperAdmin123!"),
            ("jean.simple", "jean.simple@unionflow.com", "Jean123!"),
            ("tech.lead", "tech.lead@unionflow.com", "TechLead123!"),
            ("rh.manager", "rh.manager@unionflow.com", "RhManager123!")
        ]
        
        success_count = 0
        working_users = []
        
        for username, email, password in users:
            if self.create_working_user("unionflow", username, email, password):
                success_count += 1
                working_users.append((username, password))
            print()
        
        print("=" * 80)
        print(f"📊 RÉSULTAT FINAL: {success_count}/{len(users)} comptes fonctionnent")
        print("=" * 80)
        
        if success_count > 0:
            print()
            print("🎉 SUCCÈS ! LES COMPTES SUIVANTS FONCTIONNENT :")
            print()
            for username, password in working_users:
                print(f"   ✅ {username} / {password}")
            
            print()
            print("🚀 PRÊT POUR L'APPLICATION MOBILE UNIONFLOW !")
            print()
            print("📱 TESTEZ MAINTENANT SUR VOTRE SAMSUNG :")
            print("   1. Ouvrez l'app UnionFlow")
            print("   2. Cliquez sur 'Se connecter avec Keycloak'")
            print(f"   3. Utilisez: {working_users[0][0]} / {working_users[0][1]}")
            print("   4. Vérifiez que l'authentification fonctionne")
            print()
            print("✅ ARCHITECTURE RÔLES UNIONFLOW OPÉRATIONNELLE !")
            
            # Test final de tous les comptes
            print()
            print("🧪 VÉRIFICATION FINALE DE TOUS LES COMPTES :")
            for username, email, password in users:
                if self.test_user_auth("unionflow", username, password):
                    print(f"   ✅ {username}")
                else:
                    print(f"   ❌ {username}")
            
            return True
        else:
            print()
            print("❌ Aucun compte ne fonctionne")
            print()
            print("🔧 SOLUTION MANUELLE :")
            print("1. Ouvrez http://localhost:8180/admin/")
            print("2. Connectez-vous comme admin/admin")
            print("3. Allez dans le realm 'unionflow'")
            print("4. Créez manuellement l'utilisateur 'marie.active'")
            print("5. Email: marie.active@unionflow.com")
            print("6. Mot de passe: Marie123! (non temporaire)")
            print("7. Testez avec votre application mobile")
            
            return False


def main():
    setup = WorkingSetup()
    success = setup.setup_all_users()
    
    if success:
        print()
        print("=" * 80)
        print("🎯 CONFIGURATION TERMINÉE AVEC SUCCÈS !")
        print("   Tous les comptes doivent maintenant fonctionner.")
        print("   Testez avec: python test_auth.py")
        print("=" * 80)
    else:
        print()
        print("=" * 80)
        print("⚠️  Configuration partiellement réussie")
        print("   Suivez les instructions manuelles ci-dessus")
        print("=" * 80)


if __name__ == "__main__":
    main()
