#!/usr/bin/env python
"""
Script de diagnostic pour django-modeltranslation
Placez ce fichier à la racine de votre projet Django et exécutez :
python check_translation.py
"""

import os
import sys
import django

# Configuration Django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django.setup()

from django.conf import settings
from django.apps import apps


def print_header(text):
    """Affiche un en-tête formaté"""
    print("\n" + "=" * 60)
    print(f"  {text}")
    print("=" * 60)


def check_modeltranslation_installed():
    """Vérifie si modeltranslation est installé"""
    print_header("1. Vérification de l'installation")

    try:
        import modeltranslation
        print(f"✅ django-modeltranslation est installé (version {modeltranslation.__version__})")
        return True
    except ImportError:
        print("❌ django-modeltranslation n'est PAS installé")
        print("\nPour l'installer :")
        print("  pip install django-modeltranslation")
        return False


def check_installed_apps_order():
    """Vérifie l'ordre dans INSTALLED_APPS"""
    print_header("2. Vérification de l'ordre dans INSTALLED_APPS")

    installed_apps = settings.INSTALLED_APPS

    try:
        modeltranslation_index = installed_apps.index('modeltranslation')
        core_index = installed_apps.index('core')

        if modeltranslation_index < core_index:
            print(
                f"✅ Ordre correct : modeltranslation (index {modeltranslation_index}) avant core (index {core_index})")
            return True
        else:
            print(f"❌ ERREUR : modeltranslation (index {modeltranslation_index}) est APRÈS core (index {core_index})")
            print("\n⚠️ CORRECTION REQUISE dans config/settings.py :")
            print("INSTALLED_APPS = [")
            print("    'django.contrib.admin',")
            print("    'django.contrib.auth',")
            print("    'django.contrib.contenttypes',")
            print("    'django.contrib.sessions',")
            print("    'django.contrib.messages',")
            print("    'django.contrib.staticfiles',")
            print("    'modeltranslation',  # ← AVANT core")
            print("    'rosetta',")
            print("    'core',  # ← APRÈS modeltranslation")
            print("]")
            return False
    except ValueError as e:
        print(f"❌ Erreur : {e}")
        return False


def check_translation_fields():
    """Vérifie si les champs de traduction existent dans la base de données"""
    print_header("3. Vérification des champs de traduction dans les modèles")

    from core.models import Service

    # Liste des champs attendus
    expected_fields = [
        'titre_fr', 'titre_en',
        'description_courte_fr', 'description_courte_en',
        'description_complete_fr', 'description_complete_en',
    ]

    model_fields = [field.name for field in Service._meta.get_fields()]

    print("\nChamps trouvés dans le modèle Service :")
    print(f"  Total : {len(model_fields)} champs")

    missing_fields = []
    found_fields = []

    for field in expected_fields:
        if field in model_fields:
            found_fields.append(field)
        else:
            missing_fields.append(field)

    if found_fields:
        print(f"\n✅ Champs de traduction trouvés ({len(found_fields)}) :")
        for field in found_fields:
            print(f"    - {field}")

    if missing_fields:
        print(f"\n❌ Champs de traduction manquants ({len(missing_fields)}) :")
        for field in missing_fields:
            print(f"    - {field}")
        print("\n⚠️ ACTIONS REQUISES :")
        print("  1. Supprimer les anciennes migrations :")
        print("     rm core/migrations/0*.py")
        print("  2. Créer de nouvelles migrations :")
        print("     python manage.py makemigrations core")
        print("  3. Appliquer les migrations :")
        print("     python manage.py migrate")
        print("  4. Mettre à jour les champs de traduction :")
        print("     python manage.py update_translation_fields")
        return False

    return True


def check_translation_registration():
    """Vérifie si les modèles sont enregistrés pour la traduction"""
    print_header("4. Vérification de l'enregistrement des traductions")

    try:
        from modeltranslation.translator import translator
        from core.models import Service, Certification, Projet, Temoignage, Configuration

        models_to_check = [
            ('Service', Service),
            ('Certification', Certification),
            ('Projet', Projet),
            ('Temoignage', Temoignage),
            ('Configuration', Configuration),
        ]

        all_registered = True

        for model_name, model in models_to_check:
            try:
                opts = translator.get_options_for_model(model)
                fields = opts.fields
                print(f"✅ {model_name:20} : {', '.join(fields)}")
            except Exception as e:
                print(f"❌ {model_name:20} : Non enregistré ({e})")
                all_registered = False

        return all_registered

    except Exception as e:
        print(f"❌ Erreur lors de la vérification : {e}")
        return False


def check_configuration():
    """Vérifie la configuration dans settings.py"""
    print_header("5. Vérification de la configuration")

    config_ok = True

    # MODELTRANSLATION_DEFAULT_LANGUAGE
    default_lang = getattr(settings, 'MODELTRANSLATION_DEFAULT_LANGUAGE', None)
    if default_lang:
        print(f"✅ MODELTRANSLATION_DEFAULT_LANGUAGE = '{default_lang}'")
    else:
        print("❌ MODELTRANSLATION_DEFAULT_LANGUAGE non défini")
        config_ok = False

    # MODELTRANSLATION_LANGUAGES
    languages = getattr(settings, 'MODELTRANSLATION_LANGUAGES', None)
    if languages:
        print(f"✅ MODELTRANSLATION_LANGUAGES = {languages}")
    else:
        print("❌ MODELTRANSLATION_LANGUAGES non défini")
        config_ok = False

    # MODELTRANSLATION_TRANSLATION_FILES
    translation_files = getattr(settings, 'MODELTRANSLATION_TRANSLATION_FILES', None)
    if translation_files:
        print(f"✅ MODELTRANSLATION_TRANSLATION_FILES = {translation_files}")
    else:
        print("⚠️ MODELTRANSLATION_TRANSLATION_FILES non défini (optionnel)")

    return config_ok


def main():
    """Fonction principale"""
    print("\n" + "=" * 60)
    print("  DIAGNOSTIC DJANGO-MODELTRANSLATION - VIGILUS NETTOYAGE")
    print("=" * 60)

    checks = [
        check_modeltranslation_installed(),
        check_installed_apps_order(),
        check_translation_registration(),
        check_configuration(),
        check_translation_fields(),
    ]

    print_header("RÉSUMÉ")

    if all(checks):
        print("✅ Toutes les vérifications sont passées !")
        print("\nSi les champs de traduction n'apparaissent toujours pas dans l'admin :")
        print("  1. Redémarrer le serveur : python manage.py runserver")
        print("  2. Vider le cache du navigateur (Ctrl+Shift+Delete)")
        print("  3. Utiliser un navigateur privé/incognito")
    else:
        print("❌ Certaines vérifications ont échoué.")
        print("\nSuivez les instructions ci-dessus pour corriger les problèmes.")

    print("\n" + "=" * 60)


if __name__ == '__main__':
    main()