# Generated by Django 5.0.4 on 2024-05-13 07:55

from django.db import migrations


def fix_tags_names(apps, schema_editor):
    Tag = apps.get_model("taggit", "Tag")

    for tag in Tag.objects.all():
        tag.name = tag.name.replace("-", " ")
        tag.name = tag.name.replace("_", " ")

        if not tag.name[0].isupper():
            tag.name = tag.name[0].upper() + tag.name[1:]

        if Tag.objects.filter(name=tag.name).exists():
            # Workaround
            tag.name += " "

            if Tag.objects.filter(name=tag.name).exists():
                tag.name += " "

                if Tag.objects.filter(name=tag.name).exists():
                    print(f"Tag {tag.name} already exists.")
                    continue

        try:
            tag.save()
        except Exception:
            # The tag already exists, despite numerous checks
            pass


class Migration(migrations.Migration):
    dependencies = [
        ("shared", "0004_sharedtaggedelectionsarticle"),
    ]

    operations = [migrations.RunPython(fix_tags_names)]