"""Script de validation de la configuration FastAPI."""
import sys
from pathlib import Path
from typing import List, Tuple


def check_file_exists(filepath: str, description: str) -> Tuple[bool, str]:
    """
    Vérifie qu'un fichier existe.
    
    Args:
        filepath: Chemin du fichier à vérifier.
        description: Description du fichier.
        
    Returns:
        Tuple (succès, message).
    """
    path = Path(filepath)
    if path.exists() and path.is_file():
        return True, f"✅ {description}: {filepath}"
    else:
        return False, f"❌ {description} manquant: {filepath}"


def check_directory_exists(dirpath: str, description: str) -> Tuple[bool, str]:
    """
    Vérifie qu'un répertoire existe.
    
    Args:
        dirpath: Chemin du répertoire à vérifier.
        description: Description du répertoire.
        
    Returns:
        Tuple (succès, message).
    """
    path = Path(dirpath)
    if path.exists() and path.is_dir():
        return True, f"✅ {description}: {dirpath}"
    else:
        return False, f"❌ {description} manquant: {dirpath}"


def validate_backend_structure() -> bool:
    """
    Valide la structure du backend.
    
    Returns:
        True si toutes les validations passent, False sinon.
    """
    print("🔍 Validation de la structure du backend...")
    print("=" * 60)
    
    all_passed = True
    results = []
    
    # Vérifier la structure des répertoires
    directories = [
        ("backend/", "Répertoire backend"),
        ("backend/app/", "Répertoire app"),
        ("backend/app/models/", "Répertoire models"),
        ("backend/app/schemas/", "Répertoire schemas"),
        ("backend/app/api/", "Répertoire api"),
        ("backend/app/api/v1/", "Répertoire api/v1"),
        ("backend/alembic/", "Répertoire alembic"),
        ("backend/alembic/versions/", "Répertoire alembic/versions"),
        ("backend/tests/", "Répertoire tests"),
    ]
    
    for dirpath, description in directories:
        success, message = check_directory_exists(dirpath, description)
        results.append(message)
        if not success:
            all_passed = False
    
    # Vérifier les fichiers Python
    python_files = [
        ("backend/app/__init__.py", "app/__init__.py"),
        ("backend/app/main.py", "app/main.py"),
        ("backend/app/database.py", "app/database.py"),
        ("backend/app/models/__init__.py", "models/__init__.py"),
        ("backend/app/models/user.py", "models/user.py"),
        ("backend/app/schemas/__init__.py", "schemas/__init__.py"),
        ("backend/app/schemas/user.py", "schemas/user.py"),
        ("backend/app/api/__init__.py", "api/__init__.py"),
        ("backend/app/api/v1/__init__.py", "api/v1/__init__.py"),
        ("backend/app/api/v1/users.py", "api/v1/users.py"),
        ("backend/requirements.txt", "requirements.txt"),
        ("backend/alembic.ini", "alembic.ini"),
        ("backend/alembic/env.py", "alembic/env.py"),
        ("backend/tests/__init__.py", "tests/__init__.py"),
        ("backend/tests/test_directory_structure.py", "tests/test_directory_structure.py"),
    ]
    
    for filepath, description in python_files:
        success, message = check_file_exists(filepath, description)
        results.append(message)
        if not success:
            all_passed = False
    
    # Afficher les résultats
    for result in results:
        print(result)
    
    print("=" * 60)
    
    if all_passed:
        print("✅ Toutes les validations ont réussi !")
        print("\n📋 Prochaines étapes:")
        print("1. Installer les dépendances: pip install -r backend/requirements.txt")
        print("2. Appliquer les migrations: cd backend && alembic upgrade head")
        print("3. Démarrer le serveur: cd backend && uvicorn app.main:app --reload")
        print("4. Accéder à la documentation: http://localhost:8000/docs")
    else:
        print("❌ Certaines validations ont échoué. Veuillez vérifier les erreurs ci-dessus.")
    
    return all_passed


def main():
    """Fonction principale."""
    try:
        success = validate_backend_structure()
        sys.exit(0 if success else 1)
    except Exception as e:
        print(f"❌ Erreur lors de la validation: {e}")
        sys.exit(1)


if __name__ == "__main__":
    main()
