"""
Démo visuelle des thèmes Web Sentinel
Affiche tous les thèmes disponibles dans des fenêtres séparées pour comparaison
"""

import tkinter as tk
from tkinter import ttk
import sys
from pathlib import Path

# Ajouter le dossier parent au path
sys.path.insert(0, str(Path(__file__).parent.parent))

from web_sentinel.gui.themes import ThemeManager


def create_demo_window(theme_name: str, position: tuple):
    """Crée une fenêtre de démonstration pour un thème."""
    root = tk.Tk()
    root.title(f"Web Sentinel - Thème: {theme_name.upper()}")
    root.geometry(f"500x600+{position[0]}+{position[1]}")
    
    style = ttk.Style()
    ThemeManager.apply_theme(root, style, theme_name)
    
    # Frame principal
    main_frame = ttk.Frame(root, padding="20")
    main_frame.pack(fill=tk.BOTH, expand=True)
    
    # Titre
    title = ttk.Label(main_frame, 
                     text=f"🎨 Thème: {theme_name.upper()}",
                     style="Title.TLabel")
    title.pack(pady=(0, 20))
    
    # Card de démo
    card = ttk.Frame(main_frame, style="Card.TFrame", padding="15")
    card.pack(fill=tk.X, pady=10)
    
    ttk.Label(card, text="🔍 Configuration du scan", style="Subtitle.TLabel").pack(anchor="w")
    
    # Checkbox
    check_var = tk.BooleanVar(value=True)
    ttk.Checkbutton(card, text="✓ Analyser les en-têtes HTTP", 
                   variable=check_var).pack(anchor="w", pady=5)
    
    # Entry
    ttk.Label(card, text="Domaine cible:", style="Secondary.TLabel").pack(anchor="w", pady=(10, 2))
    entry = ttk.Entry(card, width=40)
    entry.insert(0, "example.com")
    entry.pack(fill=tk.X, pady=5)
    
    # Boutons
    button_frame = ttk.Frame(main_frame)
    button_frame.pack(fill=tk.X, pady=20)
    
    ttk.Button(button_frame, text="🚀 Scanner", 
              style="Accent.TButton").pack(side=tk.LEFT, padx=5)
    ttk.Button(button_frame, text="✅ Valider", 
              style="Success.TButton").pack(side=tk.LEFT, padx=5)
    ttk.Button(button_frame, text="❌ Annuler", 
              style="Danger.TButton").pack(side=tk.LEFT, padx=5)
    
    # Résultats (Treeview)
    results_frame = ttk.LabelFrame(main_frame, text="📊 Résultats du scan", padding="10")
    results_frame.pack(fill=tk.BOTH, expand=True, pady=10)
    
    tree = ttk.Treeview(results_frame, 
                        columns=("severity", "finding"), 
                        show="tree headings",
                        height=8)
    tree.heading("severity", text="Sévérité")
    tree.heading("finding", text="Vulnérabilité")
    tree.column("#0", width=0, stretch=False)
    tree.column("severity", width=100)
    tree.column("finding", width=300)
    
    # Configurer les tags avec les couleurs du thème
    theme = ThemeManager.get_theme(theme_name)
    if theme:
        colors = theme.colors
        tree.tag_configure("critical", 
                          background=colors.critical_bg, 
                          foreground=colors.critical_fg)
        tree.tag_configure("high", 
                          background=colors.high_bg, 
                          foreground=colors.high_fg)
        tree.tag_configure("medium", 
                          background=colors.medium_bg, 
                          foreground=colors.medium_fg)
        tree.tag_configure("low", 
                          background=colors.low_bg, 
                          foreground=colors.low_fg)
        tree.tag_configure("info", 
                          background=colors.info_severity_bg, 
                          foreground=colors.info_severity_fg)
    
    # Données d'exemple
    tree.insert("", "end", values=("CRITICAL", "Certificat TLS expiré"), tags=("critical",))
    tree.insert("", "end", values=("HIGH", "En-tête HSTS manquant"), tags=("high",))
    tree.insert("", "end", values=("MEDIUM", "Version serveur exposée"), tags=("medium",))
    tree.insert("", "end", values=("LOW", "Cookie sans flag Secure"), tags=("low",))
    tree.insert("", "end", values=("INFO", "HTTPS correctement configuré"), tags=("info",))
    
    tree.pack(fill=tk.BOTH, expand=True)
    
    # Barre de statut
    status_frame = ttk.Frame(main_frame)
    status_frame.pack(fill=tk.X, pady=(10, 0))
    ttk.Label(status_frame, text=f"✅ Thème '{theme_name}' appliqué", 
             style="Success.TLabel").pack(side=tk.LEFT)
    
    return root


def main():
    """Lance la démo de tous les thèmes."""
    print("🎨 Démo des thèmes Web Sentinel")
    print("=" * 50)
    
    themes = ThemeManager.get_theme_names()
    print(f"📋 {len(themes)} thèmes disponibles\n")
    
    # Positions des fenêtres (disposition en grille)
    positions = [
        (50, 50),      # default
        (600, 50),     # dark
        (1150, 50),    # cyberpunk
        (50, 700),     # nord
        (600, 700),    # ocean
        (1150, 700),   # forest
    ]
    
    windows = []
    for i, theme_name in enumerate(themes):
        print(f"  • Création de la fenêtre pour le thème '{theme_name}'...")
        if i < len(positions):
            window = create_demo_window(theme_name, positions[i])
            windows.append(window)
    
    print(f"\n✅ {len(windows)} fenêtres créées")
    print("💡 Comparez les thèmes côte à côte !")
    print("   Fermez une fenêtre pour quitter toutes les autres.\n")
    
    # Lancer la boucle principale pour toutes les fenêtres
    if windows:
        # Quand la première fenêtre est fermée, tout se ferme
        windows[0].protocol("WM_DELETE_WINDOW", lambda: [w.destroy() for w in windows])
        windows[0].mainloop()


if __name__ == "__main__":
    main()
