#!/usr/bin/env python3
"""
Test simple des améliorations du SuggestionManager.
Vérifie la syntaxe et la structure sans dépendances lourdes.
"""

import sys
import ast


def test_syntax():
    """Vérifie que le fichier est syntaxiquement correct."""
    print("\n1. Test de syntaxe")
    print("=" * 60)
    
    try:
        with open("geniusia2/core/suggestion_manager.py", "r") as f:
            code = f.read()
        
        ast.parse(code)
        print("✓ Syntaxe correcte")
        return True
    except SyntaxError as e:
        print(f"✗ Erreur de syntaxe: {e}")
        return False


def test_methods_exist():
    """Vérifie que les nouvelles méthodes existent."""
    print("\n2. Test de présence des méthodes")
    print("=" * 60)
    
    try:
        with open("geniusia2/core/suggestion_manager.py", "r") as f:
            code = f.read()
        
        required_methods = [
            "check_workflow_match",
            "create_workflow_suggestion",
            "_track_workflow_rejection",
            "_track_workflow_acceptance",
            "_apply_priority_adjustment"
        ]
        
        all_found = True
        for method in required_methods:
            if f"def {method}" in code:
                print(f"  ✓ {method} trouvée")
            else:
                print(f"  ✗ {method} manquante")
                all_found = False
        
        return all_found
    except Exception as e:
        print(f"✗ Erreur: {e}")
        return False


def test_imports():
    """Vérifie que les imports nécessaires sont présents."""
    print("\n3. Test des imports")
    print("=" * 60)
    
    try:
        with open("geniusia2/core/suggestion_manager.py", "r") as f:
            code = f.read()
        
        required_imports = [
            "from .workflow_matcher import WorkflowMatcher, WorkflowMatch",
            "from typing import Dict, Any, Optional, Callable, List"
        ]
        
        all_found = True
        for imp in required_imports:
            if imp in code:
                print(f"  ✓ {imp}")
            else:
                print(f"  ✗ {imp} manquant")
                all_found = False
        
        return all_found
    except Exception as e:
        print(f"✗ Erreur: {e}")
        return False


def test_init_parameters():
    """Vérifie que __init__ a le paramètre workflow_matcher."""
    print("\n4. Test des paramètres __init__")
    print("=" * 60)
    
    try:
        with open("geniusia2/core/suggestion_manager.py", "r") as f:
            code = f.read()
        
        if "workflow_matcher: Optional[WorkflowMatcher]" in code:
            print("  ✓ Paramètre workflow_matcher ajouté")
        else:
            print("  ✗ Paramètre workflow_matcher manquant")
            return False
        
        if "self.workflow_matcher = workflow_matcher or WorkflowMatcher" in code:
            print("  ✓ Initialisation de workflow_matcher")
        else:
            print("  ✗ Initialisation de workflow_matcher manquante")
            return False
        
        if "self.workflow_rejections: Dict[str, int]" in code:
            print("  ✓ Tracking des rejets initialisé")
        else:
            print("  ✗ Tracking des rejets manquant")
            return False
        
        if "self.workflow_priority_adjustments: Dict[str, float]" in code:
            print("  ✓ Ajustements de priorité initialisés")
        else:
            print("  ✗ Ajustements de priorité manquants")
            return False
        
        return True
    except Exception as e:
        print(f"✗ Erreur: {e}")
        return False


def test_rejection_tracking_logic():
    """Vérifie la logique de tracking des rejets."""
    print("\n5. Test de la logique de tracking")
    print("=" * 60)
    
    try:
        with open("geniusia2/core/suggestion_manager.py", "r") as f:
            code = f.read()
        
        # Vérifier que _track_workflow_rejection incrémente le compteur
        if "current_rejections += 1" in code:
            print("  ✓ Incrémentation du compteur de rejets")
        else:
            print("  ✗ Incrémentation du compteur manquante")
            return False
        
        # Vérifier l'ajustement après 3 rejets
        if "if current_rejections >= 3:" in code:
            print("  ✓ Vérification du seuil de 3 rejets")
        else:
            print("  ✗ Vérification du seuil manquante")
            return False
        
        # Vérifier le facteur d'ajustement
        if "0.9 ** (current_rejections // 3)" in code:
            print("  ✓ Calcul du facteur d'ajustement")
        else:
            print("  ✗ Calcul du facteur manquant")
            return False
        
        return True
    except Exception as e:
        print(f"✗ Erreur: {e}")
        return False


def test_acceptance_tracking_logic():
    """Vérifie la logique de tracking des acceptations."""
    print("\n6. Test de la logique d'acceptation")
    print("=" * 60)
    
    try:
        with open("geniusia2/core/suggestion_manager.py", "r") as f:
            code = f.read()
        
        # Vérifier que _track_workflow_acceptance réduit le compteur
        if "current_rejections - 2" in code:
            print("  ✓ Réduction du compteur de rejets")
        else:
            print("  ✗ Réduction du compteur manquante")
            return False
        
        # Vérifier la suppression de l'ajustement si < 3 rejets
        if "del self.workflow_priority_adjustments[workflow_id]" in code:
            print("  ✓ Suppression de l'ajustement")
        else:
            print("  ✗ Suppression de l'ajustement manquante")
            return False
        
        return True
    except Exception as e:
        print(f"✗ Erreur: {e}")
        return False


def test_accept_reject_integration():
    """Vérifie l'intégration dans accept/reject_suggestion."""
    print("\n7. Test de l'intégration accept/reject")
    print("=" * 60)
    
    try:
        with open("geniusia2/core/suggestion_manager.py", "r") as f:
            code = f.read()
        
        # Vérifier que accept_suggestion appelle _track_workflow_acceptance
        if 'if suggestion.get("type") == "workflow":' in code and "_track_workflow_acceptance" in code:
            print("  ✓ accept_suggestion intégré")
        else:
            print("  ✗ accept_suggestion non intégré")
            return False
        
        # Vérifier que reject_suggestion appelle _track_workflow_rejection
        if "_track_workflow_rejection" in code:
            print("  ✓ reject_suggestion intégré")
        else:
            print("  ✗ reject_suggestion non intégré")
            return False
        
        return True
    except Exception as e:
        print(f"✗ Erreur: {e}")
        return False


def test_requirements_coverage():
    """Vérifie que les requirements sont couverts."""
    print("\n8. Test de couverture des requirements")
    print("=" * 60)
    
    requirements = {
        "1.4": "check_workflow_match pour vérification périodique",
        "1.5": "create_workflow_suggestion avec détails",
        "3.3": "Tracking des rejets et ajustement après 3 rejets",
        "3.5": "Filtrage par fenêtre (via WorkflowMatcher)"
    }
    
    try:
        with open("geniusia2/core/suggestion_manager.py", "r") as f:
            code = f.read()
        
        checks = {
            "1.4": "check_workflow_match" in code,
            "1.5": "create_workflow_suggestion" in code and "next_steps_preview" in code,
            "3.3": "_track_workflow_rejection" in code and "current_rejections >= 3" in code,
            "3.5": "workflow_matcher" in code
        }
        
        all_covered = True
        for req_id, description in requirements.items():
            if checks[req_id]:
                print(f"  ✓ Requirement {req_id}: {description}")
            else:
                print(f"  ✗ Requirement {req_id}: {description}")
                all_covered = False
        
        return all_covered
    except Exception as e:
        print(f"✗ Erreur: {e}")
        return False


def main():
    """Fonction principale."""
    print("\n" + "=" * 60)
    print("Test des améliorations du SuggestionManager")
    print("=" * 60)
    
    tests = [
        test_syntax,
        test_methods_exist,
        test_imports,
        test_init_parameters,
        test_rejection_tracking_logic,
        test_acceptance_tracking_logic,
        test_accept_reject_integration,
        test_requirements_coverage
    ]
    
    results = []
    for test in tests:
        try:
            result = test()
            results.append(result)
        except Exception as e:
            print(f"\n✗ Erreur dans {test.__name__}: {e}")
            import traceback
            traceback.print_exc()
            results.append(False)
    
    # Résumé
    print("\n" + "=" * 60)
    print("RÉSUMÉ")
    print("=" * 60)
    passed = sum(results)
    total = len(results)
    print(f"Tests réussis: {passed}/{total}")
    
    if passed == total:
        print("\n✓ Tous les tests sont passés!")
        print("\nLes améliorations suivantes ont été implémentées:")
        print("  1. check_workflow_match() - Vérification périodique des workflows")
        print("  2. create_workflow_suggestion() - Création de suggestions détaillées")
        print("  3. Tracking des rejets par workflow")
        print("  4. Ajustement de priorité après 3 rejets (confiance * 0.9)")
        print("  5. Tracking des acceptations pour récompenser les bons workflows")
        return 0
    else:
        print(f"\n✗ {total - passed} test(s) échoué(s)")
        return 1


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