#!/usr/bin/env python3
"""
Test rapide pour vérifier que le fix de workflow fonctionne.
"""

import sys
from pathlib import Path

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

from core.logger import Logger
from core.config import get_config
from core.vision_analysis import VisionAnalysis
from core.embeddings_manager import EmbeddingsManager
from core.utils.vision_utils import VisionUtils
from core.llm_manager import LLMManager
import numpy as np


def test_vision_analysis_fix():
    """Test que VisionAnalysis n'a plus le bug d'attribut."""
    print("\n🧪 Test 1: VisionAnalysis attribute fix")
    print("=" * 60)
    
    try:
        logger = Logger()
        embeddings = EmbeddingsManager()
        vision = VisionUtils()
        llm = LLMManager(logger=logger, fallback_to_vision=True)
        
        analyzer = VisionAnalysis(
            embeddings_manager=embeddings,
            vision_utils=vision,
            llm_manager=llm,
            logger=logger
        )
        
        # Créer un screenshot factice
        screenshot = np.random.randint(0, 255, (800, 600, 3), dtype=np.uint8)
        
        # Analyser une action
        signature = analyzer.analyze_action(
            screenshot=screenshot,
            x=100,
            y=100,
            action_type="mouse_click",
            window="Test Window"
        )
        
        # Vérifier que la signature est valide
        assert signature is not None, "Signature should not be None"
        assert "position" in signature, "Signature should have position"
        assert "embedding" in signature, "Signature should have embedding"
        assert "element_type" in signature, "Signature should have element_type"
        
        print("✅ VisionAnalysis fonctionne correctement")
        print(f"   - Position: {signature['position']}")
        print(f"   - Element type: {signature['element_type']}")
        print(f"   - Has embedding: {signature['embedding'] is not None}")
        
        return True
        
    except AttributeError as e:
        print(f"❌ AttributeError détecté: {e}")
        return False
    except Exception as e:
        print(f"⚠️  Autre erreur: {e}")
        import traceback
        traceback.print_exc()
        return False


def test_orchestrator_integration():
    """Test que l'Orchestrator a bien SessionManager et WorkflowDetector."""
    print("\n🧪 Test 2: Orchestrator integration")
    print("=" * 60)
    
    try:
        from core.orchestrator import Orchestrator
        from core.learning_manager import LearningManager
        
        logger = Logger()
        config = get_config()
        embeddings = EmbeddingsManager()
        learning = LearningManager(embeddings, logger, config)
        vision = VisionUtils()
        llm = LLMManager(logger=logger, fallback_to_vision=True)
        
        orchestrator = Orchestrator(
            learning_manager=learning,
            vision_utils=vision,
            llm_manager=llm,
            logger=logger,
            gui=None,
            config=config
        )
        
        # Vérifier que les composants sont présents
        assert hasattr(orchestrator, 'session_manager'), "Orchestrator should have session_manager"
        assert hasattr(orchestrator, 'workflow_detector'), "Orchestrator should have workflow_detector"
        assert orchestrator.session_manager is not None, "session_manager should not be None"
        assert orchestrator.workflow_detector is not None, "workflow_detector should not be None"
        
        # Vérifier que EventCapture utilise les mêmes instances
        assert orchestrator.event_capture.session_manager is orchestrator.session_manager, \
            "EventCapture should use Orchestrator's session_manager"
        assert orchestrator.event_capture.workflow_detector is orchestrator.workflow_detector, \
            "EventCapture should use Orchestrator's workflow_detector"
        
        print("✅ Orchestrator intégration OK")
        print(f"   - SessionManager: {orchestrator.session_manager}")
        print(f"   - WorkflowDetector: {orchestrator.workflow_detector}")
        print(f"   - EventCapture uses same instances: ✓")
        
        return True
        
    except Exception as e:
        print(f"❌ Erreur: {e}")
        import traceback
        traceback.print_exc()
        return False


def test_suggestion_manager_workflow():
    """Test que SuggestionManager a la méthode on_workflow_detected."""
    print("\n🧪 Test 3: SuggestionManager workflow support")
    print("=" * 60)
    
    try:
        from core.suggestion_manager import SuggestionManager
        from core.learning_manager import LearningManager
        
        logger = Logger()
        config = get_config()
        embeddings = EmbeddingsManager()
        learning = LearningManager(embeddings, logger, config)
        
        suggestion_mgr = SuggestionManager(
            learning_manager=learning,
            embeddings_manager=embeddings,
            logger=logger,
            config=config
        )
        
        # Vérifier que la méthode existe
        assert hasattr(suggestion_mgr, 'on_workflow_detected'), \
            "SuggestionManager should have on_workflow_detected method"
        
        # Tester l'appel
        test_workflow = {
            "workflow_id": "test_123",
            "name": "Test Workflow",
            "confidence": 0.85
        }
        
        suggestion_mgr.on_workflow_detected(test_workflow)
        
        print("✅ SuggestionManager workflow support OK")
        print(f"   - on_workflow_detected method exists: ✓")
        print(f"   - Method callable: ✓")
        
        return True
        
    except Exception as e:
        print(f"❌ Erreur: {e}")
        import traceback
        traceback.print_exc()
        return False


def main():
    """Point d'entrée principal."""
    print("\n" + "=" * 60)
    print("🔧 TEST DU FIX DE WORKFLOW DETECTION")
    print("=" * 60)
    
    results = []
    
    # Test 1: VisionAnalysis fix
    results.append(("VisionAnalysis fix", test_vision_analysis_fix()))
    
    # Test 2: Orchestrator integration
    results.append(("Orchestrator integration", test_orchestrator_integration()))
    
    # Test 3: SuggestionManager workflow
    results.append(("SuggestionManager workflow", test_suggestion_manager_workflow()))
    
    # Résumé
    print("\n" + "=" * 60)
    print("📊 RÉSUMÉ DES TESTS")
    print("=" * 60)
    
    passed = sum(1 for _, result in results if result)
    total = len(results)
    
    for name, result in results:
        status = "✅ PASS" if result else "❌ FAIL"
        print(f"{status}: {name}")
    
    print(f"\n🎯 Score: {passed}/{total} tests réussis")
    
    if passed == total:
        print("\n🎉 Tous les tests sont passés !")
        print("\n💡 Prochaine étape:")
        print("   Lance GeniusIA et teste avec la calculatrice:")
        print("   cd geniusia2 && ./run.sh --mode shadow")
        return 0
    else:
        print("\n⚠️  Certains tests ont échoué")
        return 1


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