#!/usr/bin/env python3
"""
🎨 Interface graphique moderne pour l'environnement de test Web Sentinel
Interface web moderne avec FastAPI et interface graphique de gestion complète
"""

import sys
import os
import json
import asyncio
import threading
import webbrowser
from pathlib import Path
from datetime import datetime, timedelta
from typing import Dict, List, Any, Optional
import subprocess

# Ajouter le répertoire parent pour importer web_sentinel
sys.path.insert(0, str(Path(__file__).parent.parent))

# Essayer les imports GUI
try:
    import tkinter as tk
    from tkinter import ttk, messagebox, filedialog
    TKINTER_AVAILABLE = True
except ImportError:
    TKINTER_AVAILABLE = False

# Essayer FastAPI pour interface web
try:
    import fastapi
    from fastapi import FastAPI, Request, Form
    from fastapi.responses import HTMLResponse, JSONResponse
    from fastapi.staticfiles import StaticFiles
    from fastapi.templating import Jinja2Templates
    import uvicorn
    FASTAPI_AVAILABLE = True
except ImportError:
    FASTAPI_AVAILABLE = False

class TestEnvironmentGUI:
    """Interface graphique principale pour l'environnement de test"""
    
    def __init__(self):
        self.base_dir = Path(__file__).parent
        
        # Initialiser les gestionnaires
        from test_accounts import TestAccountManager
        from generate_test_license import TestLicenseGenerator
        from test_scenarios import TestScenarios
        from database_setup import TestDatabaseSetup
        from metrics_simulator import MetricsSimulator
        from test_orchestrator import TestOrchestrator
        
        self.account_manager = TestAccountManager()
        self.license_generator = TestLicenseGenerator()
        self.scenarios = TestScenarios()
        self.database = TestDatabaseSetup()
        self.metrics = MetricsSimulator()
        self.orchestrator = TestOrchestrator()
        
        self.root = None
        self.status_var = None
        
    def create_tkinter_gui(self):
        """Créer l'interface Tkinter"""
        if not TKINTER_AVAILABLE:
            print("❌ Tkinter non disponible")
            return False
        
        self.root = tk.Tk()
        self.root.title("🧪 Web Sentinel Test Environment")
        self.root.geometry("1400x900")
        self.root.minsize(1200, 700)
        
        # Style
        style = ttk.Style()
        style.theme_use('clam')
        
        # Variables
        self.status_var = tk.StringVar(value="🟢 Environnement prêt")
        
        self.create_main_layout()
        return True
    
    def create_main_layout(self):
        """Créer le layout principal"""
        # Frame principal
        main_frame = ttk.Frame(self.root, padding="10")
        main_frame.pack(fill=tk.BOTH, expand=True)
        
        # Header
        self.create_header(main_frame)
        
        # Notebook avec onglets
        self.notebook = ttk.Notebook(main_frame)
        self.notebook.pack(fill=tk.BOTH, expand=True, pady=(10, 0))
        
        # Créer les onglets
        self.create_dashboard_tab()
        self.create_accounts_tab()
        self.create_licenses_tab()
        self.create_scenarios_tab()
        self.create_database_tab()
        self.create_metrics_tab()
        self.create_tests_tab()
        self.create_docker_tab()
        
        # Status bar
        self.create_status_bar(main_frame)
    
    def create_header(self, parent):
        """Créer l'en-tête"""
        header_frame = ttk.Frame(parent)
        header_frame.pack(fill=tk.X, pady=(0, 10))
        
        # Titre
        title_label = ttk.Label(header_frame, text="🧪 Web Sentinel Test Environment", 
                               font=("Arial", 16, "bold"))
        title_label.pack(side=tk.LEFT)
        
        # Boutons rapides
        buttons_frame = ttk.Frame(header_frame)
        buttons_frame.pack(side=tk.RIGHT)
        
        ttk.Button(buttons_frame, text="🌐 Interface Web", 
                  command=self.launch_web_interface).pack(side=tk.LEFT, padx=(0, 5))
        ttk.Button(buttons_frame, text="🔄 Actualiser", 
                  command=self.refresh_all).pack(side=tk.LEFT, padx=(0, 5))
        ttk.Button(buttons_frame, text="ℹ️ Aide", 
                  command=self.show_help).pack(side=tk.LEFT)
    
    def create_dashboard_tab(self):
        """Onglet tableau de bord"""
        dashboard_frame = ttk.Frame(self.notebook)
        self.notebook.add(dashboard_frame, text="📊 Dashboard")
        
        # Statistiques rapides
        stats_frame = ttk.LabelFrame(dashboard_frame, text="📈 Statistiques", padding="10")
        stats_frame.pack(fill=tk.X, padx=10, pady=5)
        
        # Grid pour les stats
        self.stats_labels = {}
        stats = [
            ("comptes", "👥 Comptes de test"),
            ("licences", "📄 Licences générées"),
            ("scenarios", "🎯 Scénarios exécutés"),
            ("tests", "🧪 Tests réussis")
        ]
        
        for i, (key, label) in enumerate(stats):
            ttk.Label(stats_frame, text=label, font=("Arial", 10, "bold")).grid(
                row=0, column=i, padx=20, pady=5, sticky=tk.W)
            self.stats_labels[key] = ttk.Label(stats_frame, text="0", 
                                              font=("Arial", 14, "bold"), foreground="blue")
            self.stats_labels[key].grid(row=1, column=i, padx=20, pady=5)
        
        # Actions rapides
        actions_frame = ttk.LabelFrame(dashboard_frame, text="🚀 Actions rapides", padding="10")
        actions_frame.pack(fill=tk.X, padx=10, pady=5)
        
        actions_grid = ttk.Frame(actions_frame)
        actions_grid.pack(fill=tk.X)
        
        quick_actions = [
            ("Setup environnement", self.quick_setup, "🔧"),
            ("Générer licence Bruno", self.quick_bruno_license, "📝"),
            ("Lancer tests unitaires", self.quick_unit_tests, "🧪"),
            ("Démarrer métriques", self.quick_start_metrics, "📊"),
            ("Vérifier Docker", self.quick_check_docker, "🐳"),
            ("Ouvrir logs", self.quick_open_logs, "📋")
        ]
        
        for i, (text, command, emoji) in enumerate(quick_actions):
            row, col = divmod(i, 3)
            btn = ttk.Button(actions_grid, text=f"{emoji} {text}", command=command)
            btn.grid(row=row, column=col, padx=5, pady=5, sticky=tk.EW)
        
        actions_grid.columnconfigure(0, weight=1)
        actions_grid.columnconfigure(1, weight=1)
        actions_grid.columnconfigure(2, weight=1)
        
        # Log rapide
        log_frame = ttk.LabelFrame(dashboard_frame, text="📋 Activité récente", padding="10")
        log_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=5)
        
        self.activity_text = tk.Text(log_frame, height=15, wrap=tk.WORD, 
                                   font=("Consolas", 9))
        scrollbar = ttk.Scrollbar(log_frame, orient=tk.VERTICAL, command=self.activity_text.yview)
        self.activity_text.configure(yscrollcommand=scrollbar.set)
        
        self.activity_text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        
        self.log_activity("🚀 Interface de test initialisée")
    
    def create_accounts_tab(self):
        """Onglet gestion des comptes"""
        accounts_frame = ttk.Frame(self.notebook)
        self.notebook.add(accounts_frame, text="👥 Comptes")
        
        # Contrôles
        controls_frame = ttk.Frame(accounts_frame)
        controls_frame.pack(fill=tk.X, padx=10, pady=5)
        
        ttk.Button(controls_frame, text="🔄 Actualiser", 
                  command=self.refresh_accounts).pack(side=tk.LEFT, padx=(0, 5))
        ttk.Button(controls_frame, text="➕ Nouveau compte", 
                  command=self.create_account).pack(side=tk.LEFT, padx=(0, 5))
        ttk.Button(controls_frame, text="✏️ Modifier", 
                  command=self.edit_account).pack(side=tk.LEFT, padx=(0, 5))
        
        # Liste des comptes
        list_frame = ttk.LabelFrame(accounts_frame, text="📋 Comptes de test", padding="10")
        list_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=5)
        
        # Treeview pour les comptes
        columns = ("Email", "Tier", "Statut", "Expire", "Domaines")
        self.accounts_tree = ttk.Treeview(list_frame, columns=columns, show="headings", height=15)
        
        for col in columns:
            self.accounts_tree.heading(col, text=col)
            self.accounts_tree.column(col, width=200)
        
        accounts_scrollbar = ttk.Scrollbar(list_frame, orient=tk.VERTICAL, 
                                         command=self.accounts_tree.yview)
        self.accounts_tree.configure(yscrollcommand=accounts_scrollbar.set)
        
        self.accounts_tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        accounts_scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        
        # Double-clic pour éditer
        self.accounts_tree.bind("<Double-1>", lambda e: self.edit_account())
    
    def create_licenses_tab(self):
        """Onglet gestion des licences"""
        licenses_frame = ttk.Frame(self.notebook)
        self.notebook.add(licenses_frame, text="📄 Licences")
        
        # Contrôles licences
        lic_controls = ttk.Frame(licenses_frame)
        lic_controls.pack(fill=tk.X, padx=10, pady=5)
        
        ttk.Button(lic_controls, text="📝 Générer licence", 
                  command=self.generate_license_dialog).pack(side=tk.LEFT, padx=(0, 5))
        ttk.Button(lic_controls, text="✅ Valider licence", 
                  command=self.validate_license_dialog).pack(side=tk.LEFT, padx=(0, 5))
        ttk.Button(lic_controls, text="📂 Ouvrir dossier", 
                  command=self.open_licenses_folder).pack(side=tk.LEFT, padx=(0, 5))
        
        # Liste des licences
        lic_list_frame = ttk.LabelFrame(licenses_frame, text="📋 Licences générées", padding="10")
        lic_list_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=5)
        
        lic_columns = ("Fichier", "Utilisateur", "Tier", "Créé", "Expire", "Statut")
        self.licenses_tree = ttk.Treeview(lic_list_frame, columns=lic_columns, show="headings", height=20)
        
        for col in lic_columns:
            self.licenses_tree.heading(col, text=col)
            self.licenses_tree.column(col, width=150)
        
        lic_scrollbar = ttk.Scrollbar(lic_list_frame, orient=tk.VERTICAL, 
                                    command=self.licenses_tree.yview)
        self.licenses_tree.configure(yscrollcommand=lic_scrollbar.set)
        
        self.licenses_tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        lic_scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
    
    def create_scenarios_tab(self):
        """Onglet scénarios de test"""
        scenarios_frame = ttk.Frame(self.notebook)
        self.notebook.add(scenarios_frame, text="🎯 Scénarios")
        
        # Liste des scénarios
        scenarios_list = [
            ("license_expiry", "Test expiration licence", "Teste le comportement à l'expiration"),
            ("premium_upgrade", "Montée en gamme", "Test passage FREE → PRO"),
            ("enterprise_features", "Fonctionnalités Enterprise", "Test fonctions avancées"),
            ("government_airgap", "Déploiement isolé", "Test mode gouvernement"),
            ("finance_compliance", "Conformité financière", "Test requirements finance"),
            ("medical_hipaa", "Conformité médicale", "Test HIPAA compliance")
        ]
        
        for i, (scenario_id, name, description) in enumerate(scenarios_list):
            scenario_frame = ttk.LabelFrame(scenarios_frame, text=f"🎯 {name}", padding="10")
            scenario_frame.pack(fill=tk.X, padx=10, pady=5)
            
            desc_label = ttk.Label(scenario_frame, text=description, font=("Arial", 9))
            desc_label.pack(side=tk.LEFT, fill=tk.X, expand=True)
            
            ttk.Button(scenario_frame, text="▶️ Exécuter", 
                      command=lambda sid=scenario_id: self.run_scenario(sid)).pack(side=tk.RIGHT, padx=(10, 0))
    
    def create_database_tab(self):
        """Onglet base de données"""
        db_frame = ttk.Frame(self.notebook)
        self.notebook.add(db_frame, text="🗄️ Base de données")
        
        # Contrôles BDD
        db_controls = ttk.Frame(db_frame)
        db_controls.pack(fill=tk.X, padx=10, pady=5)
        
        ttk.Button(db_controls, text="🔧 Setup BDD", 
                  command=self.setup_database).pack(side=tk.LEFT, padx=(0, 5))
        ttk.Button(db_controls, text="📊 Statistiques", 
                  command=self.show_db_stats).pack(side=tk.LEFT, padx=(0, 5))
        ttk.Button(db_controls, text="🧹 Nettoyer", 
                  command=self.cleanup_database).pack(side=tk.LEFT, padx=(0, 5))
        
        # Statut BDD
        self.db_status_label = ttk.Label(db_frame, text="🔴 Base de données non configurée", 
                                        font=("Arial", 10, "bold"))
        self.db_status_label.pack(pady=10)
        
        # Informations BDD
        db_info_frame = ttk.LabelFrame(db_frame, text="ℹ️ Informations base de données", padding="10")
        db_info_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=5)
        
        self.db_info_text = tk.Text(db_info_frame, height=20, wrap=tk.WORD, font=("Consolas", 9))
        db_scrollbar = ttk.Scrollbar(db_info_frame, orient=tk.VERTICAL, command=self.db_info_text.yview)
        self.db_info_text.configure(yscrollcommand=db_scrollbar.set)
        
        self.db_info_text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        db_scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
    
    def create_metrics_tab(self):
        """Onglet métriques"""
        metrics_frame = ttk.Frame(self.notebook)
        self.notebook.add(metrics_frame, text="📊 Métriques")
        
        # Contrôles métriques
        metrics_controls = ttk.Frame(metrics_frame)
        metrics_controls.pack(fill=tk.X, padx=10, pady=5)
        
        ttk.Button(metrics_controls, text="▶️ Démarrer simulation", 
                  command=self.start_metrics_simulation).pack(side=tk.LEFT, padx=(0, 5))
        ttk.Button(metrics_controls, text="⏹️ Arrêter simulation", 
                  command=self.stop_metrics_simulation).pack(side=tk.LEFT, padx=(0, 5))
        ttk.Button(metrics_controls, text="📸 Snapshot", 
                  command=self.create_metrics_snapshot).pack(side=tk.LEFT, padx=(0, 5))
        
        # Statut métriques
        self.metrics_status = ttk.Label(metrics_frame, text="⏹️ Simulation arrêtée", 
                                       font=("Arial", 10, "bold"))
        self.metrics_status.pack(pady=10)
        
        # Dashboard métriques
        metrics_dashboard = ttk.LabelFrame(metrics_frame, text="📊 Dashboard temps réel", padding="10")
        metrics_dashboard.pack(fill=tk.BOTH, expand=True, padx=10, pady=5)
        
        self.metrics_text = tk.Text(metrics_dashboard, height=20, wrap=tk.WORD, font=("Consolas", 9))
        metrics_scrollbar = ttk.Scrollbar(metrics_dashboard, orient=tk.VERTICAL, 
                                        command=self.metrics_text.yview)
        self.metrics_text.configure(yscrollcommand=metrics_scrollbar.set)
        
        self.metrics_text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        metrics_scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
    
    def create_tests_tab(self):
        """Onglet tests orchestrés"""
        tests_frame = ttk.Frame(self.notebook)
        self.notebook.add(tests_frame, text="🧪 Tests")
        
        # Suites de tests
        test_suites = [
            ("unit", "Tests unitaires", "Tests des composants individuels"),
            ("integration", "Tests d'intégration", "Tests d'intégration des composants"),
            ("license", "Tests de licence", "Tests complets du système de licence"),
            ("performance", "Tests de performance", "Tests de charge et performance"),
            ("security", "Tests de sécurité", "Tests de sécurité et pénétration"),
            ("e2e", "Tests end-to-end", "Tests bout en bout complets")
        ]
        
        for suite_id, name, description in test_suites:
            suite_frame = ttk.LabelFrame(tests_frame, text=f"🧪 {name}", padding="10")
            suite_frame.pack(fill=tk.X, padx=10, pady=5)
            
            desc_label = ttk.Label(suite_frame, text=description, font=("Arial", 9))
            desc_label.pack(side=tk.LEFT, fill=tk.X, expand=True)
            
            ttk.Button(suite_frame, text="▶️ Lancer", 
                      command=lambda sid=suite_id: self.run_test_suite(sid)).pack(side=tk.RIGHT, padx=(10, 0))
        
        # Bouton tous les tests
        all_tests_frame = ttk.Frame(tests_frame)
        all_tests_frame.pack(fill=tk.X, padx=10, pady=10)
        
        ttk.Button(all_tests_frame, text="🚀 Lancer tous les tests", 
                  command=self.run_all_tests, style="Accent.TButton").pack()
    
    def create_docker_tab(self):
        """Onglet Docker"""
        docker_frame = ttk.Frame(self.notebook)
        self.notebook.add(docker_frame, text="🐳 Docker")
        
        # Contrôles Docker
        docker_controls = ttk.Frame(docker_frame)
        docker_controls.pack(fill=tk.X, padx=10, pady=5)
        
        ttk.Button(docker_controls, text="▶️ Démarrer services", 
                  command=self.start_docker_services).pack(side=tk.LEFT, padx=(0, 5))
        ttk.Button(docker_controls, text="⏹️ Arrêter services", 
                  command=self.stop_docker_services).pack(side=tk.LEFT, padx=(0, 5))
        ttk.Button(docker_controls, text="🔄 Redémarrer", 
                  command=self.restart_docker_services).pack(side=tk.LEFT, padx=(0, 5))
        ttk.Button(docker_controls, text="📋 Statut", 
                  command=self.check_docker_status).pack(side=tk.LEFT, padx=(0, 5))
        
        # Services Docker
        services_frame = ttk.LabelFrame(docker_frame, text="🔧 Services", padding="10")
        services_frame.pack(fill=tk.X, padx=10, pady=5)
        
        services = [
            ("MySQL Test", "Base de données test", "localhost:3307"),
            ("Redis Test", "Cache test", "localhost:6380"),
            ("OWASP ZAP", "Tests sécurité", "localhost:8081"),
            ("Nginx Test", "Sites de test", "localhost:8082")
        ]
        
        for i, (name, description, port) in enumerate(services):
            service_frame = ttk.Frame(services_frame)
            service_frame.pack(fill=tk.X, pady=2)
            
            ttk.Label(service_frame, text=f"🔧 {name}", font=("Arial", 10, "bold")).pack(side=tk.LEFT)
            ttk.Label(service_frame, text=f"({port})", font=("Arial", 9)).pack(side=tk.LEFT, padx=(5, 0))
            ttk.Label(service_frame, text=description, font=("Arial", 9)).pack(side=tk.LEFT, padx=(10, 0))
        
        # Logs Docker
        logs_frame = ttk.LabelFrame(docker_frame, text="📋 Logs Docker", padding="10")
        logs_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=5)
        
        self.docker_logs_text = tk.Text(logs_frame, height=15, wrap=tk.WORD, font=("Consolas", 9))
        docker_logs_scrollbar = ttk.Scrollbar(logs_frame, orient=tk.VERTICAL, 
                                            command=self.docker_logs_text.yview)
        self.docker_logs_text.configure(yscrollcommand=docker_logs_scrollbar.set)
        
        self.docker_logs_text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        docker_logs_scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
    
    def create_status_bar(self, parent):
        """Créer la barre de statut"""
        status_frame = ttk.Frame(parent)
        status_frame.pack(fill=tk.X, pady=(10, 0))
        
        ttk.Label(status_frame, textvariable=self.status_var).pack(side=tk.LEFT)
        
        # Indicateurs
        ttk.Label(status_frame, text=f"📁 {self.base_dir}").pack(side=tk.RIGHT)
    
    # Actions rapides
    def quick_setup(self):
        """Setup rapide de l'environnement"""
        self.log_activity("🔧 Setup environnement en cours...")
        
        def setup_thread():
            try:
                # Générer configurations
                from config_generator import ConfigGenerator
                generator = ConfigGenerator()
                generator.create_all_configs()
                
                # Setup base de données
                self.database.setup_complete_test_environment()
                
                self.log_activity("✅ Setup environnement terminé")
                self.update_status("🟢 Environnement configuré")
                
            except Exception as e:
                self.log_activity(f"❌ Erreur setup: {e}")
                self.update_status("🔴 Erreur configuration")
        
        threading.Thread(target=setup_thread, daemon=True).start()
    
    def quick_bruno_license(self):
        """Générer licence pour Bruno rapidement"""
        try:
            result = self.license_generator.generate_test_license("bruno@taaazzz-prog.fr", "PRO")
            if result.get("success"):
                self.log_activity("✅ Licence PRO générée pour bruno@taaazzz-prog.fr")
                messagebox.showinfo("Succès", "Licence PRO générée pour Bruno")
            else:
                self.log_activity(f"❌ Échec génération licence: {result.get('error', 'Unknown')}")
        except Exception as e:
            self.log_activity(f"❌ Erreur génération licence: {e}")
    
    def quick_unit_tests(self):
        """Lancer tests unitaires rapidement"""
        self.run_test_suite("unit")
    
    def quick_start_metrics(self):
        """Démarrer métriques rapidement"""
        self.start_metrics_simulation()
    
    def quick_check_docker(self):
        """Vérifier statut Docker"""
        self.check_docker_status()
    
    def quick_open_logs(self):
        """Ouvrir dossier logs"""
        logs_path = self.base_dir / "logs"
        if logs_path.exists():
            if sys.platform == "win32":
                os.startfile(logs_path)
            else:
                subprocess.run(["xdg-open", str(logs_path)])
        else:
            messagebox.showwarning("Attention", "Dossier logs introuvable")
    
    # Méthodes utilitaires
    def log_activity(self, message: str):
        """Logger une activité"""
        if hasattr(self, 'activity_text'):
            timestamp = datetime.now().strftime("%H:%M:%S")
            self.activity_text.insert(tk.END, f"[{timestamp}] {message}\n")
            self.activity_text.see(tk.END)
    
    def update_status(self, status: str):
        """Mettre à jour le statut"""
        if self.status_var:
            self.status_var.set(status)
    
    def refresh_all(self):
        """Actualiser toutes les données"""
        self.refresh_accounts()
        self.refresh_licenses()
        self.refresh_stats()
        self.log_activity("🔄 Interface actualisée")
    
    def refresh_accounts(self):
        """Actualiser la liste des comptes"""
        # Effacer l'arbre
        for item in self.accounts_tree.get_children():
            self.accounts_tree.delete(item)
        
        # Recharger les comptes
        try:
            accounts = self.account_manager.list_accounts()
            for account in accounts:
                self.accounts_tree.insert("", "end", values=(
                    account["email"],
                    account["tier"],
                    account["status"],
                    account.get("license_expires", "N/A"),
                    f"{account.get('domains_used', 0)}/{account.get('domain_limit', 'N/A')}"
                ))
        except Exception as e:
            self.log_activity(f"❌ Erreur actualisation comptes: {e}")
    
    def refresh_licenses(self):
        """Actualiser la liste des licences"""
        # Effacer l'arbre
        for item in self.licenses_tree.get_children():
            self.licenses_tree.delete(item)
        
        # Scanner dossier licences
        licenses_dir = self.base_dir / "licenses"
        if licenses_dir.exists():
            for license_file in licenses_dir.glob("*.lic"):
                try:
                    # Analyser le nom du fichier
                    parts = license_file.stem.split("_")
                    if len(parts) >= 3:
                        user = parts[0] + "@" + parts[1] + "." + parts[2]
                        tier = parts[3] if len(parts) > 3 else "Unknown"
                    else:
                        user = "Unknown"
                        tier = "Unknown"
                    
                    stat = license_file.stat()
                    created = datetime.fromtimestamp(stat.st_ctime).strftime("%Y-%m-%d")
                    
                    self.licenses_tree.insert("", "end", values=(
                        license_file.name,
                        user,
                        tier,
                        created,
                        "N/A",  # Expire (would need to parse license)
                        "✅ Valid"
                    ))
                except Exception:
                    continue
    
    def refresh_stats(self):
        """Actualiser les statistiques"""
        try:
            # Compter comptes
            accounts = self.account_manager.list_accounts()
            self.stats_labels["comptes"].config(text=str(len(accounts)))
            
            # Compter licences
            licenses_dir = self.base_dir / "licenses"
            license_count = len(list(licenses_dir.glob("*.lic"))) if licenses_dir.exists() else 0
            self.stats_labels["licences"].config(text=str(license_count))
            
            # TODO: Implémenter compteurs scénarios et tests
            self.stats_labels["scenarios"].config(text="6")
            self.stats_labels["tests"].config(text="--")
            
        except Exception as e:
            self.log_activity(f"❌ Erreur actualisation stats: {e}")
    
    # Actions des onglets
    def run_scenario(self, scenario_id: str):
        """Exécuter un scénario"""
        self.log_activity(f"🎯 Exécution scénario: {scenario_id}")
        
        def run_thread():
            try:
                if hasattr(self.scenarios, f"run_{scenario_id}_test"):
                    method = getattr(self.scenarios, f"run_{scenario_id}_test")
                    result = method()
                    
                    if result.get("success"):
                        self.log_activity(f"✅ Scénario {scenario_id} réussi")
                    else:
                        self.log_activity(f"❌ Scénario {scenario_id} échoué: {result.get('error', 'Unknown')}")
                else:
                    self.log_activity(f"❌ Scénario {scenario_id} non trouvé")
                    
            except Exception as e:
                self.log_activity(f"❌ Erreur scénario {scenario_id}: {e}")
        
        threading.Thread(target=run_thread, daemon=True).start()
    
    def run_test_suite(self, suite_id: str):
        """Exécuter une suite de tests"""
        self.log_activity(f"🧪 Exécution suite: {suite_id}")
        
        def test_thread():
            try:
                result = self.orchestrator.run_test_suite(suite_id)
                success_rate = result.get("success_rate", 0)
                
                if success_rate >= 80:
                    self.log_activity(f"✅ Suite {suite_id}: {success_rate}% réussis")
                else:
                    self.log_activity(f"⚠️ Suite {suite_id}: {success_rate}% réussis")
                    
            except Exception as e:
                self.log_activity(f"❌ Erreur suite {suite_id}: {e}")
        
        threading.Thread(target=test_thread, daemon=True).start()
    
    def run_all_tests(self):
        """Exécuter tous les tests"""
        self.log_activity("🚀 Exécution de tous les tests...")
        
        def all_tests_thread():
            try:
                result = self.orchestrator.run_all_tests()
                success_rate = result.get("global_success_rate", 0)
                
                if success_rate >= 80:
                    self.log_activity(f"✅ Tous tests: {success_rate}% réussis")
                    messagebox.showinfo("Succès", f"Tests terminés: {success_rate}% de réussite")
                else:
                    self.log_activity(f"⚠️ Tous tests: {success_rate}% réussis")
                    messagebox.showwarning("Attention", f"Tests terminés: {success_rate}% de réussite")
                    
            except Exception as e:
                self.log_activity(f"❌ Erreur tests globaux: {e}")
                messagebox.showerror("Erreur", f"Erreur lors des tests: {e}")
        
        threading.Thread(target=all_tests_thread, daemon=True).start()
    
    # Méthodes de placeholder (à implémenter)
    def create_account(self):
        messagebox.showinfo("Info", "Fonctionnalité en cours de développement")
    
    def edit_account(self):
        messagebox.showinfo("Info", "Fonctionnalité en cours de développement")
    
    def generate_license_dialog(self):
        messagebox.showinfo("Info", "Fonctionnalité en cours de développement")
    
    def validate_license_dialog(self):
        messagebox.showinfo("Info", "Fonctionnalité en cours de développement")
    
    def open_licenses_folder(self):
        licenses_path = self.base_dir / "licenses"
        if licenses_path.exists():
            if sys.platform == "win32":
                os.startfile(licenses_path)
            else:
                subprocess.run(["xdg-open", str(licenses_path)])
    
    def setup_database(self):
        self.log_activity("🗄️ Setup base de données...")
        
        def db_setup_thread():
            try:
                result = self.database.setup_complete_test_environment()
                if result:
                    self.log_activity("✅ Base de données configurée")
                    self.db_status_label.config(text="🟢 Base de données configurée")
                else:
                    self.log_activity("❌ Échec configuration base de données")
                    self.db_status_label.config(text="🔴 Échec configuration")
            except Exception as e:
                self.log_activity(f"❌ Erreur BDD: {e}")
        
        threading.Thread(target=db_setup_thread, daemon=True).start()
    
    def show_db_stats(self):
        messagebox.showinfo("Info", "Fonctionnalité en cours de développement")
    
    def cleanup_database(self):
        response = messagebox.askyesno("Confirmation", 
                                     "Êtes-vous sûr de vouloir nettoyer la base de données ?")
        if response:
            self.log_activity("🧹 Nettoyage base de données...")
            try:
                self.database.cleanup_test_data()
                self.log_activity("✅ Base de données nettoyée")
            except Exception as e:
                self.log_activity(f"❌ Erreur nettoyage: {e}")
    
    def start_metrics_simulation(self):
        self.log_activity("📊 Démarrage simulation métriques...")
        self.metrics_status.config(text="▶️ Simulation en cours")
        # TODO: Implémenter démarrage simulation
    
    def stop_metrics_simulation(self):
        self.log_activity("⏹️ Arrêt simulation métriques...")
        self.metrics_status.config(text="⏹️ Simulation arrêtée")
        # TODO: Implémenter arrêt simulation
    
    def create_metrics_snapshot(self):
        self.log_activity("📸 Création snapshot métriques...")
        try:
            self.metrics.save_metrics_snapshot()
            self.log_activity("✅ Snapshot créé")
        except Exception as e:
            self.log_activity(f"❌ Erreur snapshot: {e}")
    
    def start_docker_services(self):
        self.log_activity("🐳 Démarrage services Docker...")
        # TODO: Implémenter docker-compose up
    
    def stop_docker_services(self):
        self.log_activity("🐳 Arrêt services Docker...")
        # TODO: Implémenter docker-compose down
    
    def restart_docker_services(self):
        self.log_activity("🐳 Redémarrage services Docker...")
        # TODO: Implémenter docker-compose restart
    
    def check_docker_status(self):
        self.log_activity("🐳 Vérification statut Docker...")
        try:
            # Vérifier si docker-compose.yml existe
            compose_file = self.base_dir / "docker-compose.yml"
            if compose_file.exists():
                self.log_activity("✅ docker-compose.yml trouvé")
                # TODO: Vérifier services avec docker-compose ps
            else:
                self.log_activity("❌ docker-compose.yml non trouvé")
        except Exception as e:
            self.log_activity(f"❌ Erreur Docker: {e}")
    
    def launch_web_interface(self):
        """Lancer l'interface web"""
        if FASTAPI_AVAILABLE:
            self.log_activity("🌐 Démarrage interface web...")
            # TODO: Lancer FastAPI server
            webbrowser.open("http://localhost:8000")
        else:
            messagebox.showwarning("Attention", "FastAPI non disponible pour l'interface web")
    
    def show_help(self):
        """Afficher l'aide"""
        help_text = """
🧪 Web Sentinel Test Environment

ONGLETS DISPONIBLES:
📊 Dashboard - Vue d'ensemble et actions rapides
👥 Comptes - Gestion des comptes de test
📄 Licences - Génération et validation de licences
🎯 Scénarios - Exécution de scénarios de test
🗄️ Base de données - Gestion base de données test
📊 Métriques - Simulation métriques temps réel
🧪 Tests - Orchestrateur de tests
🐳 Docker - Gestion environnement Docker

ACTIONS RAPIDES:
🔧 Setup environnement - Configuration complète
📝 Générer licence Bruno - Licence PRO pour bruno@taaazzz-prog.fr
🧪 Tests unitaires - Validation composants
📊 Démarrer métriques - Simulation temps réel
🐳 Vérifier Docker - Statut des services
📋 Ouvrir logs - Dossier de logs

Pour plus d'informations, consultez le README.md
        """
        
        help_window = tk.Toplevel(self.root)
        help_window.title("Aide - Web Sentinel Test Environment")
        help_window.geometry("600x500")
        
        text_widget = tk.Text(help_window, wrap=tk.WORD, font=("Arial", 10))
        text_widget.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
        text_widget.insert(tk.END, help_text)
        text_widget.config(state=tk.DISABLED)
    
    def run(self):
        """Lancer l'interface"""
        if self.create_tkinter_gui():
            # Initialiser les données
            self.refresh_all()
            
            # Lancer la boucle principale
            self.root.protocol("WM_DELETE_WINDOW", self.on_closing)
            self.root.mainloop()
        else:
            print("❌ Impossible de créer l'interface graphique")
            return False
    
    def on_closing(self):
        """Gestionnaire de fermeture"""
        self.root.destroy()


def main():
    """Point d'entrée principal"""
    print("🧪 INTERFACE GRAPHIQUE TEST ENVIRONMENT")
    print("=" * 50)
    
    if not TKINTER_AVAILABLE:
        print("❌ Tkinter non disponible")
        print("💡 Suggestion: Utiliser les outils en ligne de commande")
        return
    
    try:
        app = TestEnvironmentGUI()
        app.run()
        
    except Exception as e:
        print(f"❌ Erreur inattendue: {e}")
        return


if __name__ == "__main__":
    main()