"""
Commande pour migrer les anciens CarouselButton vers le nouveau systeme Button/ButtonAssignment.
"""
from django.core.management.base import BaseCommand
from django.contrib.contenttypes.models import ContentType

from apps.core.models import CarouselSlide, CarouselButton
from cms.models import Button, ButtonAssignment
from traduction.models import Dictionnaire, Language


class Command(BaseCommand):
    help = 'Migre les CarouselButton vers le nouveau systeme Button/ButtonAssignment'

    def add_arguments(self, parser):
        parser.add_argument(
            '--dry-run',
            action='store_true',
            help='Affiche ce qui serait fait sans effectuer les modifications',
        )
        parser.add_argument(
            '--delete-old',
            action='store_true',
            help='Supprime les anciens CarouselButton apres migration',
        )

    def handle(self, *args, **options):
        dry_run = options['dry_run']
        delete_old = options['delete_old']

        if dry_run:
            self.stdout.write(self.style.WARNING('Mode dry-run: aucune modification ne sera effectuee\n'))

        # Recuperer tous les CarouselButton
        old_buttons = CarouselButton.objects.select_related('slide', 'internal_page').all()

        if not old_buttons.exists():
            self.stdout.write(self.style.SUCCESS('Aucun CarouselButton a migrer.'))
            return

        self.stdout.write(f'Boutons a migrer: {old_buttons.count()}\n')

        # ContentType pour CarouselButton (pour les traductions)
        old_content_type = ContentType.objects.get_for_model(CarouselButton)
        new_content_type = ContentType.objects.get_for_model(Button)
        slide_content_type = ContentType.objects.get_for_model(CarouselSlide)

        migrated = 0
        skipped = 0

        for old_button in old_buttons:
            self.stdout.write(f'\n--- CarouselButton #{old_button.pk}: "{old_button.text}" ---')
            self.stdout.write(f'    Slide: {old_button.slide}')
            self.stdout.write(f'    Type: {old_button.link_type}')
            self.stdout.write(f'    Style: {old_button.style}')

            # Verifier si un bouton similaire existe deja
            existing = Button.objects.filter(
                text=old_button.text,
                link_type=old_button.link_type,
                style=old_button.style
            ).first()

            if existing:
                # Verifier si l'association existe deja
                existing_assignment = ButtonAssignment.objects.filter(
                    button=existing,
                    content_type=slide_content_type,
                    object_id=old_button.slide.pk
                ).exists()

                if existing_assignment:
                    self.stdout.write(self.style.WARNING(f'    -> IGNORE: Bouton et association existent deja'))
                    skipped += 1
                    continue
                else:
                    self.stdout.write(f'    -> Bouton existe, creation de l\'association uniquement')
                    new_button = existing
            else:
                # Creer le nouveau bouton
                self.stdout.write(f'    -> Creation du nouveau bouton')

                if not dry_run:
                    new_button = Button.objects.create(
                        name=f"{old_button.slide.title[:30]} - {old_button.text[:30]}",
                        text=old_button.text,
                        link_type=old_button.link_type,
                        external_url=old_button.external_url or '',
                        internal_page=old_button.internal_page,
                        style=old_button.style,
                        active=old_button.is_active
                    )
                    self.stdout.write(self.style.SUCCESS(f'    -> Button #{new_button.pk} cree'))

                    # Migrer les traductions
                    old_translations = Dictionnaire.objects.filter(
                        content_type=old_content_type,
                        object_id=old_button.pk,
                        field='text'
                    )

                    for trans in old_translations:
                        Dictionnaire.objects.create(
                            content_type=new_content_type,
                            object_id=new_button.pk,
                            field='text',
                            language=trans.language,
                            translation=trans.translation
                        )
                        self.stdout.write(f'    -> Traduction [{trans.language.code}] migree')
                else:
                    new_button = None

            # Creer l'association ButtonAssignment
            if not dry_run and new_button:
                assignment = ButtonAssignment.objects.create(
                    button=new_button,
                    content_type=slide_content_type,
                    object_id=old_button.slide.pk,
                    order=old_button.order
                )
                self.stdout.write(self.style.SUCCESS(f'    -> ButtonAssignment #{assignment.pk} cree'))

            migrated += 1

        self.stdout.write(f'\n{"="*50}')
        self.stdout.write(f'Migration terminee:')
        self.stdout.write(f'  - Migres: {migrated}')
        self.stdout.write(f'  - Ignores: {skipped}')

        if delete_old and not dry_run and migrated > 0:
            self.stdout.write(self.style.WARNING(f'\nSuppression des anciens CarouselButton...'))
            count = CarouselButton.objects.count()
            CarouselButton.objects.all().delete()
            self.stdout.write(self.style.SUCCESS(f'{count} CarouselButton supprimes'))
        elif delete_old and dry_run:
            self.stdout.write(self.style.WARNING(f'\n[DRY-RUN] {CarouselButton.objects.count()} CarouselButton seraient supprimes'))

        self.stdout.write(self.style.SUCCESS('\nTermine!'))
