#!/usr/bin/env python3
"""
Test du Mode Assisté avec détection de workflows
Simule un utilisateur qui répète des actions et reçoit des suggestions
"""

import sys
import time
import numpy as np
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.event_capture import EventCapture
from core.learning_manager import LearningManager
from core.embeddings_manager import EmbeddingsManager
from core.suggestion_manager import SuggestionManager


def create_mock_learning_manager():
    """Crée un mock du LearningManager pour les tests"""
    class MockEmbeddingsManager:
        def search_similar(self, embedding, k=3):
            return []  # Pas de résultats pour forcer les suggestions de workflow
    
    class MockLearningManager:
        def __init__(self):
            self.embeddings_manager = MockEmbeddingsManager()
        
        def load_task(self, task_id):
            return None
        
        def confirm_action(self, data):
            pass
    
    return MockLearningManager()


def simulate_workflow_actions(event_capture, workflow_name, base_time):
    """Simule une séquence d'actions formant un workflow"""
    
    workflows = {
        "onlyoffice": [
            {
                "type": "mouse_click",
                "action_type": "click",
                "x": 100,
                "y": 50,
                "position": (100, 50),
                "window": "Desktop",
                "description": "Ouvrir lanceur"
            },
            {
                "type": "key_press",
                "action_type": "type",
                "key": "office",
                "text": "office",
                "window": "Desktop",
                "description": "Chercher OnlyOffice"
            },
            {
                "type": "mouse_click",
                "action_type": "click",
                "x": 150,
                "y": 100,
                "position": (150, 100),
                "window": "Desktop",
                "description": "Lancer OnlyOffice"
            },
            {
                "type": "mouse_click",
                "action_type": "click",
                "x": 200,
                "y": 150,
                "position": (200, 150),
                "window": "OnlyOffice",
                "description": "Nouveau document"
            },
            {
                "type": "key_press",
                "action_type": "type",
                "key": "Bonjour",
                "text": "Bonjour",
                "window": "OnlyOffice",
                "description": "Taper du texte"
            }
        ],
        "firefox": [
            {
                "type": "mouse_click",
                "action_type": "click",
                "x": 50,
                "y": 50,
                "position": (50, 50),
                "window": "Firefox",
                "description": "Ouvrir Firefox"
            },
            {
                "type": "key_press",
                "action_type": "type",
                "key": "google.com",
                "text": "google.com",
                "window": "Firefox",
                "description": "Aller sur Google"
            },
            {
                "type": "mouse_click",
                "action_type": "click",
                "x": 300,
                "y": 200,
                "position": (300, 200),
                "window": "Firefox",
                "description": "Cliquer recherche"
            }
        ]
    }
    
    actions = workflows.get(workflow_name, [])
    
    for i, action_template in enumerate(actions):
        action = {
            **action_template,
            "timestamp": (base_time + timedelta(seconds=i*2)).isoformat()
        }
        event_capture.capture_event(action)
    
    return len(actions)


def test_workflow_learning():
    """Test 1: Apprentissage de workflows"""
    print("\n" + "="*60)
    print("🧪 TEST 1: Apprentissage de workflows")
    print("="*60)
    
    logger = Logger()
    config = get_config()
    
    event_capture = EventCapture(
        logger=logger,
        max_history=1000,
        pattern_threshold=3,
        config=config
    )
    
    print("\n📋 Simulation de 3 répétitions du workflow OnlyOffice...")
    
    for i in range(3):
        base_time = datetime.now() - timedelta(hours=3-i)
        actions_count = simulate_workflow_actions(event_capture, "onlyoffice", base_time)
        event_capture.force_finalize_session()
        print(f"   ✅ Répétition {i+1}: {actions_count} actions")
    
    # Vérifier les workflows détectés
    workflows = event_capture.get_workflows()
    
    print(f"\n📊 Résultats:")
    print(f"   Sessions: {len(event_capture.get_sessions())}")
    print(f"   Workflows détectés: {len(workflows)}")
    
    if workflows:
        for workflow in workflows:
            print(f"\n   🎉 Workflow appris:")
            print(f"      Nom: {workflow.name}")
            print(f"      Étapes: {len(workflow.steps)}")
            print(f"      Répétitions: {workflow.repetitions}")
            print(f"      Confiance: {workflow.confidence:.2%}")
        
        return True, workflows[0]
    else:
        print(f"\n   ⚠️  Aucun workflow détecté")
        return False, None


def test_workflow_suggestion(learned_workflow):
    """Test 2: Suggestion de workflow en cours"""
    print("\n" + "="*60)
    print("🧪 TEST 2: Suggestion de workflow")
    print("="*60)
    
    logger = Logger()
    config = get_config()
    
    # Créer les composants
    event_capture = EventCapture(
        logger=logger,
        max_history=1000,
        pattern_threshold=3,
        config=config
    )
    
    # Simuler que le workflow a été appris
    event_capture.workflow_detector.workflows.append(learned_workflow)
    
    # Mock du LearningManager
    class MockLearningManager:
        def __init__(self):
            pass  # Mock
        
        def load_task(self, task_id):
            return None
        
        def confirm_action(self, data):
            pass
    
    learning_manager = create_mock_learning_manager()
    
    suggestion_manager = SuggestionManager(
        learning_manager=learning_manager,
        embeddings_manager=learning_manager.embeddings_manager,
        logger=logger,
        config=config
    )
    
    print("\n📋 Simulation du début du workflow...")
    
    # Simuler les 2 premières actions du workflow
    base_time = datetime.now()
    
    action1 = {
        "type": "mouse_click",
        "action_type": "click",
        "x": 100,
        "y": 50,
        "position": (100, 50),
        "window": "Desktop",
        "timestamp": base_time.isoformat(),
        "description": "Ouvrir lanceur"
    }
    event_capture.capture_event(action1)
    print(f"   ✅ Action 1: {action1['description']}")
    
    action2 = {
        "type": "key_press",
        "action_type": "type",
        "key": "office",
        "text": "office",
        "window": "Desktop",
        "timestamp": (base_time + timedelta(seconds=2)).isoformat(),
        "description": "Chercher OnlyOffice"
    }
    event_capture.capture_event(action2)
    print(f"   ✅ Action 2: {action2['description']}")
    
    # Créer le contexte pour la suggestion
    context = {
        "event_capture": event_capture,
        "embedding": np.random.rand(512),  # Mock embedding
        "window": "Desktop",
        "timestamp": datetime.now()
    }
    
    print(f"\n🔍 Recherche de suggestion...")
    
    # Chercher une suggestion
    suggestion = suggestion_manager.find_suggestion(context)
    
    if suggestion and suggestion.get("type") == "workflow":
        print(f"\n   🎉 Suggestion de workflow trouvée !")
        print(f"      Workflow: {suggestion['workflow_name']}")
        print(f"      Étape actuelle: {suggestion['current_step']}/{suggestion['total_steps']}")
        print(f"      Prochaine action: {suggestion['next_action']['description']}")
        print(f"      Confiance: {suggestion['confidence']:.2%}")
        print(f"      Actions restantes: {suggestion['remaining_steps']}")
        
        return True
    else:
        print(f"\n   ⚠️  Aucune suggestion de workflow")
        if suggestion:
            print(f"      Type de suggestion: {suggestion.get('type')}")
        return False


def test_workflow_completion():
    """Test 3: Complétion d'un workflow avec suggestions"""
    print("\n" + "="*60)
    print("🧪 TEST 3: Complétion de workflow")
    print("="*60)
    
    logger = Logger()
    config = get_config()
    
    # Augmenter le timeout de session pour éviter la fragmentation
    config["workflow"] = config.get("workflow", {})
    config["workflow"]["session_timeout"] = 600  # 10 minutes
    
    event_capture = EventCapture(
        logger=logger,
        max_history=1000,
        pattern_threshold=3,
        config=config
    )
    
    # Apprendre un workflow simple
    print("\n📋 Phase 1: Apprentissage (3 répétitions)...")
    
    for i in range(3):
        base_time = datetime.now() - timedelta(hours=3-i)
        simulate_workflow_actions(event_capture, "firefox", base_time)
        event_capture.force_finalize_session()
        print(f"   ✅ Répétition {i+1}")
    
    # Forcer l'analyse des sessions pour détecter les workflows
    sessions = event_capture.get_sessions(10)
    event_capture.workflow_detector.analyze_sessions(sessions)
    
    workflows = event_capture.get_workflows()
    
    if not workflows:
        print(f"\n   ❌ Aucun workflow appris")
        return False
    
    print(f"   ✅ Workflow appris: {workflows[0].name}")
    
    # Mock du LearningManager
    class MockLearningManager:
        def __init__(self):
            pass  # Mock
        
        def load_task(self, task_id):
            return None
        
        def confirm_action(self, data):
            pass
    
    learning_manager = create_mock_learning_manager()
    
    suggestion_manager = SuggestionManager(
        learning_manager=learning_manager,
        embeddings_manager=learning_manager.embeddings_manager,
        logger=logger,
        config=config
    )
    
    # Simuler l'exécution du workflow avec suggestions
    print(f"\n📋 Phase 2: Exécution avec suggestions...")
    
    base_time = datetime.now()
    workflow_actions = [
        {
            "type": "mouse_click",
            "action_type": "click",
            "x": 50,
            "y": 50,
            "position": (50, 50),
            "window": "Desktop",
            "description": "Ouvrir Firefox"
        },
        {
            "type": "key_press",
            "action_type": "type",
            "key": "google.com",
            "text": "google.com",
            "window": "Firefox",
            "description": "Aller sur Google"
        }
    ]
    
    suggestions_received = 0
    
    for i, action in enumerate(workflow_actions):
        action["timestamp"] = (base_time + timedelta(seconds=i*2)).isoformat()
        event_capture.capture_event(action)
        print(f"\n   Action {i+1}: {action['description']}")
        
        # Debug: vérifier la session courante
        if event_capture.session_manager.current_session:
            session = event_capture.session_manager.current_session
            print(f"      Session courante: {session.action_count} actions")
            for j, act in enumerate(session.actions):
                print(f"         {j+1}. {act.get('action_type')} - {act.get('description')}")
        else:
            print(f"      ⚠️  Pas de session courante")
        
        # Chercher une suggestion
        context = {
            "event_capture": event_capture,
            "embedding": np.random.rand(512),
            "window": action["window"],
            "timestamp": datetime.now()
        }
        
        suggestion = suggestion_manager.find_suggestion(context)
        
        if suggestion:
            if suggestion.get("type") == "workflow":
                suggestions_received += 1
                print(f"      💡 Suggestion: {suggestion['next_action']['description']}")
                print(f"      📊 Confiance: {suggestion['confidence']:.2%}")
            else:
                print(f"      ℹ️  Suggestion type: {suggestion.get('type')}")
        else:
            print(f"      ⚠️  Aucune suggestion trouvée")
    
    print(f"\n📊 Résultats:")
    print(f"   Actions exécutées: {len(workflow_actions)}")
    print(f"   Suggestions reçues: {suggestions_received}")
    
    return suggestions_received > 0


def main():
    """Exécute tous les tests"""
    print("\n" + "="*60)
    print("🚀 TEST MODE ASSISTÉ AVEC WORKFLOWS")
    print("="*60)
    
    results = []
    learned_workflow = None
    
    try:
        # Test 1: Apprentissage
        success, workflow = test_workflow_learning()
        results.append(("Apprentissage", success))
        learned_workflow = workflow
    except Exception as e:
        print(f"\n❌ ERREUR Test 1: {e}")
        import traceback
        traceback.print_exc()
        results.append(("Apprentissage", False))
    
    if learned_workflow:
        try:
            # Test 2: Suggestion
            success = test_workflow_suggestion(learned_workflow)
            results.append(("Suggestion", success))
        except Exception as e:
            print(f"\n❌ ERREUR Test 2: {e}")
            import traceback
            traceback.print_exc()
            results.append(("Suggestion", False))
    else:
        print(f"\n⚠️  Test 2 ignoré (pas de workflow appris)")
        results.append(("Suggestion", False))
    
    try:
        # Test 3: Complétion
        success = test_workflow_completion()
        results.append(("Complétion", success))
    except Exception as e:
        print(f"\n❌ ERREUR Test 3: {e}")
        import traceback
        traceback.print_exc()
        results.append(("Complétion", 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 !")
        print("\n💡 Le Mode Assisté avec workflows fonctionne !")
        return 0
    else:
        print(f"\n⚠️  {total - passed} test(s) échoué(s)")
        return 1


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