# Generated by Django 4.2.9 on 2024-11-11 10:15

from django.db import migrations


def remove_duplicated_categories(apps, schema_editor):
    Category = apps.get_model("agenda_culturel", "Category")
    CategorisationRule = apps.get_model("agenda_culturel", "CategorisationRule")
    Event = apps.get_model("agenda_culturel", "Event")


    catnames = list(set([c.name for c in Category.objects.all()]))

    # for each category name
    for cname in catnames:
        # check if it exists more than one category
        if Category.objects.filter(name=cname).count() > 1:
            cats = Category.objects.filter(name=cname).order_by("pk")
            nbs = [Event.objects.filter(category=c).count() + CategorisationRule.objects.filter(category=c).count() for c in cats]

            # if only one category with this name has elements
            if len([n for n in nbs if n != 0]) == 1:
                # remove all categories without elements
                for n, c in zip(nbs, cats):
                    if n == 0:
                        c.delete()
            else:
                # otherwise, remove all but the last one (by ID)
                for c in cats[0:-1]:
                    c.delete()


def do_nothing(apps, schema_editor):
    pass

class Migration(migrations.Migration):

    dependencies = [
        ('agenda_culturel', '0107_strip_aliases'),
    ]

    operations = [
        migrations.RunPython(remove_duplicated_categories, reverse_code=do_nothing)
    ]
