#!/usr/bin/env python3
"""
Test de la suggestion de workflows dans le Mode Assisté
"""

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.suggestion_manager import SuggestionManager
from core.learning_manager import LearningManager
from core.embeddings_manager import EmbeddingsManager


def create_mock_learning_manager(logger, config):
    """Crée un mock du LearningManager pour les tests"""
    class MockLearningManager:
        def __init__(self):
            self.embeddings_manager = EmbeddingsManager(logger, config)
        
        def load_task(self, task_id):
            return None
        
        def confirm_action(self, data):
            pass
    
    return MockLearningManager()


def simulate_workflow_actions(event_capture, base_time):
    """
    Simule une séquence d'actions qui correspond à un workflow
    """
    actions = [
        {
            "action_type": "click",
            "position": (100, 50),
            "window": "Desktop",
            "timestamp": (base_time + timedelta(seconds=0)).isoformat(),
            "description": "Clic sur lanceur"
        },
        {
            "action_type": "type",
            "text": "office",
            "window": "Desktop",
            "timestamp": (base_time + timedelta(seconds=2)).isoformat(),
            "description": "Tape 'office'"
        },
        {
            "action_type": "click",
            "position": (150, 100),
            "window": "Desktop",
            "timestamp": (base_time + timedelta(seconds=4)).isoformat(),
            "description": "Clic sur OnlyOffice"
        }
    ]
    
    for action in actions:
        event_capture.capture_event(action)
    
    return actions


def main():
    print("\n" + "="*60)
    print("  🧪 TEST DE SUGGESTION DE WORKFLOWS")
    print("="*60 + "\n")
    
    # Initialiser les composants
    config = get_config()
    logger = Logger()
    
    # EventCapture avec workflows
    event_capture = EventCapture(
        logger=logger,
        pattern_threshold=3,
        max_history=1000,
        config=config
    )
    
    # Mock du LearningManager
    learning_manager = create_mock_learning_manager(logger, config)
    
    # SuggestionManager
    suggestion_manager = SuggestionManager(
        learning_manager=learning_manager,
        embeddings_manager=learning_manager.embeddings_manager,
        logger=logger,
        config=config
    )
    
    # Callback pour les suggestions
    suggestions_created = []
    
    def on_suggestion_created(suggestion):
        suggestions_created.append(suggestion)
        print(f"\n🎉 SUGGESTION CRÉÉE !")
        print(f"   Type: {suggestion.get('type', 'unknown')}")
        
        if suggestion.get('type') == 'workflow':
            print(f"   Workflow: {suggestion['workflow_name']}")
            print(f"   Étape: {suggestion['current_step']}/{suggestion['total_steps']}")
            print(f"   Prochaine action: {suggestion['next_action']['description']}")
            print(f"   Confiance: {suggestion['confidence']:.2%}")
            print(f"   Répétitions: {suggestion['repetitions']}x")
        else:
            print(f"   Tâche: {suggestion.get('task_name', 'Unknown')}")
            print(f"   Confiance: {suggestion['confidence']:.2%}")
    
    suggestion_manager.on_suggestion_created = on_suggestion_created
    
    print("📋 Phase 1: Créer des workflows répétés...\n")
    
    # Créer 3 sessions similaires pour établir un workflow
    base_times = [
        datetime.now() - timedelta(hours=3),
        datetime.now() - timedelta(hours=2),
        datetime.now() - timedelta(hours=1)
    ]
    
    for i, base_time in enumerate(base_times, 1):
        print(f"Session {i} - {base_time.strftime('%H:%M')}")
        
        # Créer les actions
        actions = [
            {
                "action_type": "click",
                "position": (100, 50),
                "window": "Desktop",
                "timestamp": (base_time + timedelta(seconds=0)).isoformat(),
                "description": "Clic sur lanceur"
            },
            {
                "action_type": "type",
                "text": "office",
                "window": "Desktop",
                "timestamp": (base_time + timedelta(seconds=2)).isoformat(),
                "description": "Tape 'office'"
            },
            {
                "action_type": "click",
                "position": (150, 100),
                "window": "Desktop",
                "timestamp": (base_time + timedelta(seconds=4)).isoformat(),
                "description": "Clic sur OnlyOffice"
            },
            {
                "action_type": "click",
                "position": (200, 150),
                "window": "OnlyOffice",
                "timestamp": (base_time + timedelta(seconds=8)).isoformat(),
                "description": "Nouveau document"
            },
            {
                "action_type": "type",
                "text": "Bonjour",
                "window": "OnlyOffice",
                "timestamp": (base_time + timedelta(seconds=10)).isoformat(),
                "description": "Tape du texte"
            }
        ]
        
        # Ajouter les actions
        for action in actions:
            event_capture.session_manager.add_action(action)
        
        # Finaliser la session
        event_capture.session_manager.force_finalize_session()
        
        print(f"   ✅ {len(actions)} actions ajoutées")
    
    # Analyser pour détecter des workflows
    print(f"\n🔍 Analyse des sessions pour détecter des workflows...")
    recent_sessions = event_capture.session_manager.get_recent_sessions(10)
    event_capture.workflow_detector.analyze_sessions(recent_sessions)
    
    # Vérifier les workflows détectés
    workflows = event_capture.get_workflows()
    print(f"\n📊 Workflows détectés: {len(workflows)}")
    
    if workflows:
        for workflow in workflows:
            print(f"   - {workflow.name} ({workflow.repetitions}x, {workflow.confidence:.2%})")
            print(f"     Étapes: {len(workflow.steps)}")
    else:
        print("   ❌ Aucun workflow détecté")
        print("\n⚠️  Le test ne peut pas continuer sans workflows")
        return
    
    print(f"\n📋 Phase 2: Simuler le début d'un workflow...\n")
    
    # Créer une nouvelle session qui commence comme le workflow
    print("Début d'une nouvelle session...")
    current_time = datetime.now()
    
    # Première action du workflow
    action1 = {
        "action_type": "click",
        "position": (100, 50),
        "window": "Desktop",
        "timestamp": current_time.isoformat(),
        "description": "Clic sur lanceur"
    }
    event_capture.session_manager.add_action(action1)
    print(f"   ✅ Action 1: {action1['description']}")
    
    time.sleep(0.5)
    
    # Deuxième action du workflow
    action2 = {
        "action_type": "type",
        "text": "office",
        "window": "Desktop",
        "timestamp": (current_time + timedelta(seconds=2)).isoformat(),
        "description": "Tape 'office'"
    }
    event_capture.session_manager.add_action(action2)
    print(f"   ✅ Action 2: {action2['description']}")
    
    print(f"\n🔍 Vérification de suggestion de workflow...\n")
    
    # Créer un contexte pour la suggestion
    context = {
        "event_capture": event_capture,
        "embedding": np.random.rand(512),  # Mock embedding
        "window": "Desktop",
        "timestamp": datetime.now()
    }
    
    # Chercher une suggestion
    suggestion = suggestion_manager.find_suggestion(context)
    
    if suggestion:
        print(f"✅ Suggestion trouvée !")
        print(f"   Type: {suggestion.get('type')}")
        
        if suggestion.get('type') == 'workflow':
            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"   Actions restantes: {suggestion['remaining_steps']}")
            print(f"   Confiance: {suggestion['confidence']:.2%}")
            
            # Créer la suggestion dans le manager
            suggestion_manager.create_suggestion(context)
            
            print(f"\n📈 Statistiques:")
            stats = suggestion_manager.get_stats()
            print(f"   Suggestion active: {stats['has_active_suggestion']}")
            
    else:
        print(f"❌ Aucune suggestion trouvée")
        print(f"\n🔍 Debug:")
        print(f"   Workflows: {len(workflows)}")
        print(f"   Session courante: {event_capture.session_manager.current_session}")
        if event_capture.session_manager.current_session:
            print(f"   Actions dans session: {event_capture.session_manager.current_session.action_count}")
    
    print(f"\n" + "="*60)
    print(f"  ✅ TEST TERMINÉ")
    print(f"  Suggestions créées: {len(suggestions_created)}")
    print(f"="*60)


if __name__ == "__main__":
    main()
