#!/usr/bin/env python3
"""
Test simple des workflows - Vérifie que session_manager et workflow_detector fonctionnent
"""

import sys
from pathlib import Path
from datetime import datetime, timedelta

sys.path.insert(0, str(Path(__file__).parent / "geniusia2"))

from core.logger import Logger
from core.config import get_config
from core.session_manager import SessionManager
from core.workflow_detector import WorkflowDetector


def test_session_manager():
    """Test du SessionManager"""
    print("\n" + "="*60)
    print("🧪 TEST 1: SessionManager")
    print("="*60)
    
    logger = Logger()
    config = get_config()
    
    session_manager = SessionManager(logger, config)
    
    # Créer des actions de test
    base_time = datetime.now()
    actions = [
        {
            "action_type": "click",
            "position": (100, 100),
            "window": "Test Window",
            "timestamp": base_time.isoformat(),
            "description": "Action 1"
        },
        {
            "action_type": "type",
            "text": "test",
            "window": "Test Window",
            "timestamp": (base_time + timedelta(seconds=1)).isoformat(),
            "description": "Action 2"
        },
        {
            "action_type": "click",
            "position": (200, 200),
            "window": "Test Window",
            "timestamp": (base_time + timedelta(seconds=2)).isoformat(),
            "description": "Action 3"
        }
    ]
    
    # Ajouter les actions
    for action in actions:
        session_manager.add_action(action)
    
    # Vérifier la session courante
    assert session_manager.current_session is not None, "❌ Pas de session courante"
    assert session_manager.current_session.action_count == 3, f"❌ Mauvais nombre d'actions: {session_manager.current_session.action_count}"
    
    print(f"✅ Session créée avec {session_manager.current_session.action_count} actions")
    
    # Finaliser la session
    session_manager.force_finalize_session()
    
    # Vérifier que la session est finalisée
    assert session_manager.current_session is None, "❌ Session pas finalisée"
    assert len(session_manager.sessions) == 1, f"❌ Mauvais nombre de sessions: {len(session_manager.sessions)}"
    
    print(f"✅ Session finalisée et sauvegardée")
    print(f"✅ Total sessions: {len(session_manager.sessions)}")
    
    return True


def test_workflow_detector():
    """Test du WorkflowDetector"""
    print("\n" + "="*60)
    print("🧪 TEST 2: WorkflowDetector")
    print("="*60)
    
    logger = Logger()
    config = get_config()
    
    session_manager = SessionManager(logger, config)
    workflow_detector = WorkflowDetector(logger, config)
    
    # Créer 3 sessions similaires
    print("\n📋 Création de 3 sessions similaires...")
    
    for i in range(3):
        base_time = datetime.now() - timedelta(hours=3-i)
        
        actions = [
            {
                "action_type": "click",
                "position": (100, 100),
                "window": "OnlyOffice",
                "timestamp": base_time.isoformat(),
                "description": f"Ouvrir OnlyOffice {i+1}"
            },
            {
                "action_type": "type",
                "text": "Bonjour",
                "window": "OnlyOffice",
                "timestamp": (base_time + timedelta(seconds=1)).isoformat(),
                "description": f"Taper texte {i+1}"
            },
            {
                "action_type": "click",
                "position": (200, 200),
                "window": "OnlyOffice",
                "timestamp": (base_time + timedelta(seconds=2)).isoformat(),
                "description": f"Fermer {i+1}"
            }
        ]
        
        for action in actions:
            session_manager.add_action(action)
        
        session_manager.force_finalize_session()
        print(f"   ✅ Session {i+1} créée")
    
    # Analyser les sessions
    print("\n🔍 Analyse des sessions pour détecter des workflows...")
    sessions = session_manager.get_recent_sessions(10)
    workflow_detector.analyze_sessions(sessions)
    
    # Vérifier les workflows détectés
    workflows = workflow_detector.get_workflows()
    
    print(f"\n📊 Résultats:")
    print(f"   Sessions créées: {len(sessions)}")
    print(f"   Workflows détectés: {len(workflows)}")
    
    if workflows:
        for workflow in workflows:
            print(f"\n   🎉 Workflow détecté:")
            print(f"      ID: {workflow.workflow_id}")
            print(f"      Nom: {workflow.name}")
            print(f"      Étapes: {len(workflow.steps)}")
            print(f"      Répétitions: {workflow.repetitions}")
            print(f"      Confiance: {workflow.confidence:.2%}")
        
        assert len(workflows) >= 1, "❌ Aucun workflow détecté"
        assert workflows[0].repetitions >= 3, f"❌ Pas assez de répétitions: {workflows[0].repetitions}"
        
        print(f"\n✅ Workflow détecté avec succès !")
        return True
    else:
        print(f"\n⚠️  Aucun workflow détecté")
        print(f"   Raisons possibles:")
        print(f"   - Seuil de similarité trop élevé")
        print(f"   - Pas assez de répétitions")
        return False


def test_integration():
    """Test d'intégration SessionManager + WorkflowDetector"""
    print("\n" + "="*60)
    print("🧪 TEST 3: Intégration complète")
    print("="*60)
    
    logger = Logger()
    config = get_config()
    
    # Créer de nouvelles instances pour isoler le test
    session_manager = SessionManager(logger, config)
    workflow_detector = WorkflowDetector(logger, config)
    
    # Nettoyer les workflows existants pour ce test
    workflow_detector.workflows = []
    
    # Callback pour détecter les workflows
    workflows_detected = []
    
    def on_workflow_detected(workflow):
        workflows_detected.append(workflow)
        # workflow est un dictionnaire, pas un objet
        workflow_name = workflow.get("name", "Unknown")
        print(f"\n   🎉 Callback: Workflow détecté - {workflow_name}")
    
    workflow_detector.on_workflow_detected = on_workflow_detected
    
    # Créer des sessions et détecter automatiquement
    print("\n📋 Simulation de 4 sessions similaires...")
    
    for i in range(4):
        base_time = datetime.now() - timedelta(hours=4-i)
        
        # Actions légèrement variées mais similaires
        actions = [
            {
                "action_type": "click",
                "position": (100 + i*5, 100),
                "window": "Firefox",
                "timestamp": base_time.isoformat(),
                "description": "Ouvrir Firefox"
            },
            {
                "action_type": "type",
                "text": "test",
                "window": "Firefox",
                "timestamp": (base_time + timedelta(seconds=1)).isoformat(),
                "description": "Rechercher"
            },
            {
                "action_type": "click",
                "position": (150, 150),
                "window": "Firefox",
                "timestamp": (base_time + timedelta(seconds=2)).isoformat(),
                "description": "Cliquer résultat"
            }
        ]
        
        for action in actions:
            session_manager.add_action(action)
        
        session_manager.force_finalize_session()
        
        # Analyser après chaque session
        if i >= 2:  # À partir de la 3ème session
            sessions = session_manager.get_recent_sessions(10)
            workflow_detector.analyze_sessions(sessions)
    
    print(f"\n📊 Résultats:")
    print(f"   Sessions: {len(session_manager.sessions)}")
    print(f"   Workflows: {len(workflow_detector.get_workflows())}")
    print(f"   Callbacks appelés: {len(workflows_detected)}")
    
    if workflows_detected:
        print(f"\n✅ Intégration réussie !")
        return True
    else:
        print(f"\n⚠️  Aucun workflow détecté via callback")
        return False


def main():
    """Exécute tous les tests"""
    print("\n" + "="*60)
    print("🚀 TEST DES WORKFLOWS - SIMPLE")
    print("="*60)
    
    results = []
    
    try:
        # Test 1: SessionManager
        results.append(("SessionManager", test_session_manager()))
    except Exception as e:
        print(f"\n❌ ERREUR Test 1: {e}")
        import traceback
        traceback.print_exc()
        results.append(("SessionManager", False))
    
    try:
        # Test 2: WorkflowDetector
        results.append(("WorkflowDetector", test_workflow_detector()))
    except Exception as e:
        print(f"\n❌ ERREUR Test 2: {e}")
        import traceback
        traceback.print_exc()
        results.append(("WorkflowDetector", False))
    
    try:
        # Test 3: Intégration
        results.append(("Intégration", test_integration()))
    except Exception as e:
        print(f"\n❌ ERREUR Test 3: {e}")
        import traceback
        traceback.print_exc()
        results.append(("Intégration", False))
    
    # Résumé
    print("\n" + "="*60)
    print("📊 RÉSUMÉ DES TESTS")
    print("="*60)
    
    for name, success in results:
        status = "✅" if success else "❌"
        print(f"{status} {name}")
    
    total = len(results)
    passed = sum(1 for _, success in results if success)
    
    print(f"\n📈 Score: {passed}/{total} tests réussis")
    
    if passed == total:
        print("\n🎉 TOUS LES TESTS SONT PASSÉS !")
        return 0
    else:
        print(f"\n⚠️  {total - passed} test(s) échoué(s)")
        return 1


if __name__ == "__main__":
    sys.exit(main())
