"""
Test simple du WhitelistManager sans dépendances lourdes
"""

import sys
from pathlib import Path

# Ajouter le répertoire geniusia2 au path
sys.path.insert(0, str(Path(__file__).parent / "geniusia2"))

from core.whitelist_manager import WhitelistManager
from core.logger import Logger
from core.config import ensure_directories

def test_whitelist_basic_functionality():
    """Test des fonctionnalités de base du WhitelistManager"""
    print("Test des fonctionnalités de base du WhitelistManager")
    print("=" * 60)
    
    # S'assurer que les répertoires existent
    ensure_directories()
    
    # Test 1: Créer un WhitelistManager
    print("\n1. Création du WhitelistManager:")
    logger = Logger()
    wm = WhitelistManager(logger=logger, require_admin_confirmation=False)
    print(f"   ✓ WhitelistManager créé")
    print(f"   - Chemin: {wm.whitelist_path}")
    
    # Test 2: Ajouter des fenêtres
    print("\n2. Ajout de fenêtres à la liste blanche:")
    windows_to_add = [
        "Dolibarr*",
        "Firefox*",
        "*Chrome",
        "Visual Studio Code",
        "GNOME Terminal"
    ]
    
    for window in windows_to_add:
        success = wm.add_to_whitelist(window, admin_confirmed=True, added_by="test")
        print(f"   {'✓' if success else '✗'} Ajouté: {window}")
    
    print(f"   - Total: {len(wm.get_whitelist())} entrées")
    
    # Test 3: Vérification is_window_allowed avec différents patterns
    print("\n3. Test de vérification is_window_allowed:")
    test_cases = [
        # (window_title, expected_result, description)
        ("Dolibarr - Facturation", True, "Prefix wildcard"),
        ("Dolibarr ERP", True, "Prefix wildcard"),
        ("Firefox - Mozilla", True, "Prefix wildcard"),
        ("Google Chrome", True, "Suffix wildcard"),
        ("Microsoft Edge Chrome", True, "Suffix wildcard"),
        ("Visual Studio Code", True, "Exact match"),
        ("GNOME Terminal", True, "Exact match"),
        ("Unknown Application", False, "Not in whitelist"),
        ("Notepad", False, "Not in whitelist"),
        ("", False, "Empty string"),
    ]
    
    all_passed = True
    for window, expected, description in test_cases:
        allowed = wm.is_window_allowed(window)
        passed = allowed == expected
        all_passed = all_passed and passed
        status = "✓" if passed else "✗"
        result = "Autorisé" if allowed else "Bloqué"
        print(f"   {status} {result}: '{window}' ({description})")
    
    # Test 4: Métadonnées et informations
    print("\n4. Test des métadonnées:")
    info = wm.get_entry_info("Dolibarr*")
    if info:
        print(f"   ✓ Informations pour 'Dolibarr*':")
        print(f"     - Ajouté le: {info.get('added_at')}")
        print(f"     - Ajouté par: {info.get('added_by')}")
        print(f"     - Admin confirmé: {info.get('admin_confirmed')}")
    
    # Test 5: Statistiques
    print("\n5. Statistiques:")
    stats = wm.get_statistics()
    print(f"   ✓ Total entrées: {stats['total_entries']}")
    print(f"   ✓ Avec wildcards: {stats['entries_with_wildcards']}")
    print(f"   ✓ Exactes: {stats['entries_exact']}")
    
    # Test 6: Suppression
    print("\n6. Test de suppression:")
    removed = wm.remove_from_whitelist("Firefox*")
    print(f"   ✓ Supprimé 'Firefox*': {removed}")
    
    # Vérifier que Firefox n'est plus autorisé
    allowed = wm.is_window_allowed("Firefox - Mozilla")
    print(f"   {'✓' if not allowed else '✗'} Firefox maintenant bloqué: {not allowed}")
    
    # Test 7: Patterns complexes avec wildcards
    print("\n7. Test de patterns complexes:")
    wm.clear_whitelist()
    wm.add_to_whitelist("Fire*fox", admin_confirmed=True)
    
    complex_tests = [
        ("Firefox", True),
        ("Firefoxes", True),
        ("Fire123fox", True),
        ("Firefly", False),
        ("Chrome", False)
    ]
    
    for window, expected in complex_tests:
        allowed = wm.is_window_allowed(window)
        passed = allowed == expected
        status = "✓" if passed else "✗"
        result = "Autorisé" if allowed else "Bloqué"
        print(f"   {status} {result}: '{window}'")
    
    # Test 8: Sauvegarde et rechargement
    print("\n8. Test sauvegarde et rechargement:")
    wm.clear_whitelist()
    wm.add_to_whitelist("Test Window 1", admin_confirmed=True)
    wm.add_to_whitelist("Test Window 2", admin_confirmed=True)
    wm.save_whitelist()
    print(f"   ✓ Sauvegardé: {len(wm.get_whitelist())} entrées")
    
    # Créer un nouveau manager pour tester le chargement
    wm2 = WhitelistManager(
        whitelist_path=str(wm.whitelist_path),
        logger=logger,
        require_admin_confirmation=False
    )
    print(f"   ✓ Rechargé: {len(wm2.get_whitelist())} entrées")
    
    if len(wm2.get_whitelist()) == 2:
        print(f"   ✓ Persistance vérifiée")
    else:
        print(f"   ✗ Erreur de persistance")
        all_passed = False
    
    # Test 9: Export/Import
    print("\n9. Test export/import:")
    export_path = "test_whitelist_export.json"
    success = wm.export_whitelist(export_path)
    print(f"   ✓ Exporté: {success}")
    
    wm.clear_whitelist()
    print(f"   ✓ Liste vidée: {len(wm.get_whitelist())} entrées")
    
    success = wm.import_whitelist(export_path, admin_confirmed=True)
    print(f"   ✓ Réimporté: {success}")
    print(f"   ✓ Après import: {len(wm.get_whitelist())} entrées")
    
    # Nettoyer
    import os
    if os.path.exists(export_path):
        os.remove(export_path)
        print(f"   ✓ Fichier d'export nettoyé")
    
    # Test 10: Confirmation admin
    print("\n10. Test de confirmation admin:")
    wm_admin = WhitelistManager(logger=logger, require_admin_confirmation=True)
    
    # Sans confirmation admin
    success = wm_admin.add_to_whitelist("Test Without Confirmation", admin_confirmed=False)
    print(f"   {'✓' if not success else '✗'} Rejeté sans confirmation: {not success}")
    
    # Avec confirmation admin
    success = wm_admin.add_to_whitelist("Test With Confirmation", admin_confirmed=True)
    print(f"   {'✓' if success else '✗'} Accepté avec confirmation: {success}")
    
    print("\n" + "=" * 60)
    if all_passed:
        print("✓ TOUS LES TESTS RÉUSSIS!")
    else:
        print("✗ CERTAINS TESTS ONT ÉCHOUÉ")
    print("=" * 60)
    
    return all_passed


if __name__ == "__main__":
    try:
        success = test_whitelist_basic_functionality()
        sys.exit(0 if success else 1)
    except Exception as e:
        print(f"\n✗ Erreur fatale: {e}")
        import traceback
        traceback.print_exc()
        sys.exit(1)
