"""
Exemple d'intégration des dialogues et notifications
Démontre comment utiliser tous les composants ensemble
"""

from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QVBoxLayout, QWidget
from PyQt5.QtCore import QTimer
import sys

from correction_dialog import CorrectionDialog
from post_action_notification import PostActionNotification
from transition_notification import TransitionNotification


class IntegrationDemo(QMainWindow):
    """
    Démonstration de l'intégration des dialogues et notifications
    """
    
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Démo Dialogues & Notifications")
        self.setGeometry(100, 100, 400, 500)
        
        # Widget central
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        # Layout
        layout = QVBoxLayout()
        central_widget.setLayout(layout)
        
        # Boutons de test
        btn_correction = QPushButton("1. Dialogue de Correction")
        btn_correction.clicked.connect(self.test_correction_dialog)
        layout.addWidget(btn_correction)
        
        btn_success = QPushButton("2. Notification Succès")
        btn_success.clicked.connect(self.test_success_notification)
        layout.addWidget(btn_success)
        
        btn_failure = QPushButton("3. Notification Échec")
        btn_failure.clicked.connect(self.test_failure_notification)
        layout.addWidget(btn_failure)
        
        btn_autopilot = QPushButton("4. Proposition Autopilot")
        btn_autopilot.clicked.connect(self.test_autopilot_proposal)
        layout.addWidget(btn_autopilot)
        
        btn_confidence = QPushButton("5. Alerte Baisse Confiance")
        btn_confidence.clicked.connect(self.test_confidence_drop)
        layout.addWidget(btn_confidence)
        
        btn_whitelist = QPushButton("6. Violation Liste Blanche")
        btn_whitelist.clicked.connect(self.test_whitelist_violation)
        layout.addWidget(btn_whitelist)
        
        btn_ui_change = QPushButton("7. Changement UI")
        btn_ui_change.clicked.connect(self.test_ui_change)
        layout.addWidget(btn_ui_change)
        
        btn_transition = QPushButton("8. Transition de Mode")
        btn_transition.clicked.connect(self.test_mode_transition)
        layout.addWidget(btn_transition)
        
        btn_scenario = QPushButton("9. Scénario Complet")
        btn_scenario.clicked.connect(self.test_complete_scenario)
        layout.addWidget(btn_scenario)
        
        layout.addStretch()
    
    def test_correction_dialog(self):
        """Test du dialogue de correction"""
        print("\n=== Test Dialogue de Correction ===")
        
        incorrect = {
            "label": "annuler_button",
            "confidence": 0.75,
            "bbox": (300, 400, 100, 35),
            "action_type": "click"
        }
        
        alternatives = [
            {
                "label": "valider_button",
                "confidence": 0.92,
                "bbox": (450, 400, 100, 35),
                "action_type": "click"
            },
            {
                "label": "enregistrer_button",
                "confidence": 0.88,
                "bbox": (600, 400, 120, 35),
                "action_type": "click"
            },
            {
                "label": "fermer_button",
                "confidence": 0.65,
                "bbox": (750, 50, 30, 30),
                "action_type": "click"
            }
        ]
        
        correction = CorrectionDialog.show_correction_dialog(
            incorrect,
            alternatives,
            parent=self
        )
        
        if correction:
            print(f"✓ Correction effectuée:")
            print(f"  Méthode: {correction['correction_method']}")
            print(f"  Élément corrigé: {correction['corrected_element']['label']}")
            print(f"  Élément original: {correction['original_detection']['label']}")
        else:
            print("✗ Correction annulée")
    
    def test_success_notification(self):
        """Test notification de succès"""
        print("\n=== Test Notification Succès ===")
        
        notification = PostActionNotification.show_success(
            action_type="click",
            target_element="valider_button",
            confidence=0.95,
            parent=self
        )
        
        notification.feedback_provided.connect(
            lambda result: print(f"✓ Retour reçu: {result}")
        )
    
    def test_failure_notification(self):
        """Test notification d'échec"""
        print("\n=== Test Notification Échec ===")
        
        def on_correction(data):
            print(f"✎ Correction demandée pour: {data['action_type']} sur {data['target_element']}")
        
        notification = PostActionNotification.show_failure(
            action_type="click",
            target_element="annuler_button",
            error_message="Élément non trouvé à l'écran",
            confidence=0.65,
            allow_correction=True,
            parent=self
        )
        
        notification.allow_corrective_feedback(on_correction)
        notification.feedback_provided.connect(
            lambda result: print(f"✓ Retour reçu: {result}")
        )
    
    def test_autopilot_proposal(self):
        """Test proposition autopilot"""
        print("\n=== Test Proposition Autopilot ===")
        
        notification = TransitionNotification.show_autopilot_proposal(
            task_name="Ouvrir Facture",
            observation_count=25,
            concordance_rate=0.97,
            parent=self
        )
        
        notification.action_taken.connect(
            lambda action: print(f"✓ Décision autopilot: {action}")
        )
    
    def test_confidence_drop(self):
        """Test alerte baisse de confiance"""
        print("\n=== Test Baisse de Confiance ===")
        
        notification = TransitionNotification.show_confidence_drop(
            task_name="Saisie Données",
            confidence_score=0.85,
            threshold=0.90,
            reason="Changements UI détectés",
            parent=self
        )
        
        notification.action_taken.connect(
            lambda action: print(f"✓ Action: {action}")
        )
    
    def test_whitelist_violation(self):
        """Test violation liste blanche"""
        print("\n=== Test Violation Liste Blanche ===")
        
        notification = TransitionNotification.show_whitelist_violation(
            window_title="Application Non Autorisée",
            action_type="click",
            parent=self
        )
        
        notification.action_taken.connect(
            lambda action: print(f"✓ Décision liste blanche: {action}")
        )
    
    def test_ui_change(self):
        """Test changement UI"""
        print("\n=== Test Changement UI ===")
        
        notification = TransitionNotification.show_ui_change(
            task_name="Navigation Menu",
            similarity=0.65,
            parent=self
        )
        
        notification.action_taken.connect(
            lambda action: print(f"✓ Action changement UI: {action}")
        )
    
    def test_mode_transition(self):
        """Test transition de mode"""
        print("\n=== Test Transition de Mode ===")
        
        notification = TransitionNotification.show_mode_transition(
            task_name="Export Données",
            from_mode="auto",
            to_mode="assist",
            reason="low_confidence",
            parent=self
        )
        
        notification.action_taken.connect(
            lambda action: print(f"✓ Action transition: {action}")
        )
    
    def test_complete_scenario(self):
        """Test d'un scénario complet"""
        print("\n=== Scénario Complet ===")
        print("Simulation d'un flux de travail complet avec notifications...")
        
        # 1. Notification de succès
        print("\n1. Action réussie...")
        QTimer.singleShot(500, lambda: PostActionNotification.show_success(
            "click", "ouvrir_button", 0.96, parent=self
        ))
        
        # 2. Notification d'échec avec correction
        print("2. Action échouée, correction nécessaire...")
        def show_failure():
            notif = PostActionNotification.show_failure(
                "click", "valider_button", "Élément masqué", 0.72, parent=self
            )
            notif.correction_requested.connect(
                lambda data: print(f"   → Correction demandée: {data}")
            )
        QTimer.singleShot(2000, show_failure)
        
        # 3. Alerte de changement UI
        print("3. Changement d'interface détecté...")
        def show_ui_change():
            notif = TransitionNotification.show_ui_change(
                "Ouvrir Facture", 0.68, parent=self
            )
            notif.action_taken.connect(
                lambda action: print(f"   → Décision UI: {action}")
            )
        QTimer.singleShot(4000, show_ui_change)
        
        # 4. Baisse de confiance
        print("4. Baisse de confiance détectée...")
        QTimer.singleShot(6000, lambda: TransitionNotification.show_confidence_drop(
            "Saisie Données", 0.87, 0.90, "Erreurs répétées", parent=self
        ))
        
        # 5. Proposition autopilot
        print("5. Proposition de passage en autopilot...")
        def show_autopilot():
            notif = TransitionNotification.show_autopilot_proposal(
                "Export Rapport", 22, 0.96, parent=self
            )
            notif.action_taken.connect(
                lambda action: print(f"   → Décision autopilot: {action}")
            )
        QTimer.singleShot(8000, show_autopilot)
        
        # 6. Transition de mode
        print("6. Transition de mode effectuée...")
        QTimer.singleShot(10000, lambda: TransitionNotification.show_mode_transition(
            "Export Rapport", "assist", "auto", "high_concordance", parent=self
        ))
        
        print("\nScénario lancé! Observez les notifications...")


def main():
    """Point d'entrée principal"""
    app = QApplication(sys.argv)
    
    demo = IntegrationDemo()
    demo.show()
    
    print("=== Démo Dialogues & Notifications ===")
    print("Cliquez sur les boutons pour tester chaque composant")
    print("=" * 50)
    
    sys.exit(app.exec_())


if __name__ == "__main__":
    main()
