#!/usr/bin/env python3
"""
Vérification automatique de l'état des tâches du Mode Assisté.
Compare l'état déclaré dans tasks.md avec l'implémentation réelle.
"""

import os
import re
from pathlib import Path
from typing import Dict, List, Tuple

def check_task_1_workflow_matcher() -> Tuple[bool, str]:
    """Vérifie Task 1: WorkflowMatcher."""
    file_path = Path("geniusia2/core/workflow_matcher.py")
    
    if not file_path.exists():
        return False, "Fichier workflow_matcher.py manquant"
    
    with open(file_path, 'r') as f:
        content = f.read()
    
    required_methods = [
        'match_current_session',
        'calculate_match_score',
        'find_best_match',
        '_calculate_step_similarity',
        '_calculate_position_similarity'
    ]
    
    missing = [m for m in required_methods if f"def {m}" not in content]
    
    if missing:
        return False, f"Méthodes manquantes: {', '.join(missing)}"
    
    return True, "✓ Toutes les méthodes implémentées"


def check_task_2_suggestion_manager() -> Tuple[bool, str]:
    """Vérifie Task 2: SuggestionManager amélioré."""
    file_path = Path("geniusia2/core/suggestion_manager.py")
    
    if not file_path.exists():
        return False, "Fichier suggestion_manager.py manquant"
    
    with open(file_path, 'r') as f:
        content = f.read()
    
    required_methods = [
        'check_workflow_match',
        'create_workflow_suggestion',
        '_track_workflow_rejection',
        '_track_workflow_acceptance',
        '_apply_priority_adjustment'
    ]
    
    missing = [m for m in required_methods if f"def {m}" not in content]
    
    if missing:
        return False, f"Méthodes manquantes: {', '.join(missing)}"
    
    # Vérifier les attributs de tracking
    if 'workflow_rejections' not in content:
        return False, "Attribut workflow_rejections manquant"
    
    if 'workflow_priority_adjustments' not in content:
        return False, "Attribut workflow_priority_adjustments manquant"
    
    return True, "✓ Toutes les améliorations implémentées"


def check_task_3_orchestrator() -> Tuple[bool, str]:
    """Vérifie Task 3: Intégration dans Orchestrator."""
    file_path = Path("geniusia2/core/orchestrator.py")
    
    if not file_path.exists():
        return False, "Fichier orchestrator.py manquant"
    
    with open(file_path, 'r') as f:
        content = f.read()
    
    # Vérifier la méthode _check_workflow_match
    if 'def _check_workflow_match' not in content:
        return False, "Méthode _check_workflow_match manquante"
    
    # Vérifier l'appel à check_workflow_match du SuggestionManager
    if 'suggestion_manager.check_workflow_match' not in content:
        return False, "Appel à suggestion_manager.check_workflow_match manquant"
    
    # Vérifier que c'est appelé dans check_for_suggestions
    if 'workflow_match = self._check_workflow_match()' not in content:
        return False, "Appel à _check_workflow_match manquant dans check_for_suggestions"
    
    return True, "✓ Intégration complète dans Orchestrator"


def check_task_4_gui_overlay() -> Tuple[bool, str]:
    """Vérifie Task 4: GUI Overlay amélioré."""
    file_path = Path("geniusia2/gui/suggestion_overlay.py")
    
    if not file_path.exists():
        return False, "Fichier suggestion_overlay.py manquant"
    
    with open(file_path, 'r') as f:
        content = f.read()
    
    # Vérifier l'affichage des prochaines étapes
    if 'next_steps' not in content.lower() and 'remaining_steps' not in content.lower():
        return False, "Affichage des prochaines étapes non implémenté"
    
    # Vérifier la barre de progression
    if 'progress' not in content.lower():
        return False, "Barre de progression non implémentée"
    
    return True, "✓ GUI Overlay amélioré"


def check_task_5_task_replay() -> Tuple[bool, str]:
    """Vérifie Task 5: TaskReplayEngine amélioré."""
    file_path = Path("geniusia2/core/task_replay.py")
    
    if not file_path.exists():
        return False, "Fichier task_replay.py manquant"
    
    with open(file_path, 'r') as f:
        content = f.read()
    
    # Vérifier le feedback visuel
    if 'feedback' not in content.lower() and 'highlight' not in content.lower():
        return False, "Feedback visuel non implémenté"
    
    # Vérifier l'arrêt sur échec
    if 'on_failure' not in content.lower() and 'error' not in content.lower():
        return False, "Gestion d'échec non implémentée"
    
    return True, "✓ TaskReplayEngine amélioré"


def check_task_6_timeout() -> Tuple[bool, str]:
    """Vérifie Task 6: Timeout et dismiss."""
    file_path = Path("geniusia2/core/suggestion_manager.py")
    
    if not file_path.exists():
        return False, "Fichier suggestion_manager.py manquant"
    
    with open(file_path, 'r') as f:
        content = f.read()
    
    # Vérifier la méthode check_timeout
    if 'def check_timeout' not in content:
        return False, "Méthode check_timeout manquante"
    
    # Vérifier le callback on_suggestion_timeout
    if 'on_suggestion_timeout' not in content:
        return False, "Callback on_suggestion_timeout manquant"
    
    # Vérifier le timeout de 10s
    if 'suggestion_timeout' not in content:
        return False, "Configuration suggestion_timeout manquante"
    
    return True, "✓ Timeout et dismiss implémentés"


def main():
    """Fonction principale."""
    print("\n" + "=" * 60)
    print("VÉRIFICATION DES TÂCHES - MODE ASSISTÉ")
    print("=" * 60)
    
    tasks = [
        ("1. WorkflowMatcher", check_task_1_workflow_matcher),
        ("2. SuggestionManager", check_task_2_suggestion_manager),
        ("3. Orchestrator", check_task_3_orchestrator),
        ("4. GUI Overlay", check_task_4_gui_overlay),
        ("5. TaskReplayEngine", check_task_5_task_replay),
        ("6. Timeout & Dismiss", check_task_6_timeout),
    ]
    
    results = []
    
    for task_name, check_func in tasks:
        print(f"\n{task_name}")
        print("-" * 60)
        
        try:
            success, message = check_func()
            results.append((task_name, success, message))
            
            if success:
                print(f"  ✓ COMPLÉTÉ: {message}")
            else:
                print(f"  ✗ INCOMPLET: {message}")
        except Exception as e:
            print(f"  ✗ ERREUR: {e}")
            results.append((task_name, False, str(e)))
    
    # Résumé
    print("\n" + "=" * 60)
    print("RÉSUMÉ")
    print("=" * 60)
    
    completed = sum(1 for _, success, _ in results if success)
    total = len(results)
    
    print(f"\nTâches complétées: {completed}/{total}")
    
    # Détails des tâches incomplètes
    incomplete = [(name, msg) for name, success, msg in results if not success]
    
    if incomplete:
        print("\nTâches à compléter:")
        for name, msg in incomplete:
            print(f"  • {name}: {msg}")
    else:
        print("\n✓ Toutes les tâches sont complétées!")
    
    # Recommandations
    print("\n" + "=" * 60)
    print("RECOMMANDATIONS")
    print("=" * 60)
    
    if completed == total:
        print("\n✓ Le Mode Assisté est prêt pour les tests!")
        print("\nProchaines étapes:")
        print("  1. Tester avec workflows Calculatrice (Task 7)")
        print("  2. Ajuster les seuils si nécessaire (Task 8)")
    elif completed >= 3:
        print("\n⚠ Fonctionnalités de base implémentées")
        print("  Les tâches restantes sont des améliorations UI/UX")
    else:
        print("\n✗ Fonctionnalités critiques manquantes")
        print("  Complète les tâches 1-3 en priorité")
    
    return 0 if completed >= 3 else 1


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