# Generated by Django 5.2.1 on 2025-05-13 14:55

from django.db import migrations, models

from arches.management.commands.validate import deduplicate_widgets


class Migration(migrations.Migration):

    dependencies = [
        ("models", "11848_alter_spatialview_geometrynode"),
    ]

    def fail_nicely_if_excess_widgets(apps, schema_editor):
        Node = apps.get_model("models", "Node")
        nodes_with_excess_widgets = (
            Node.objects.annotate(
                source_widget_count=models.Count(
                    "cardxnodexwidget", filter=models.Q(source_identifier__isnull=True)
                ),
                draft_widget_count=models.Count(
                    "cardxnodexwidget", filter=models.Q(source_identifier__isnull=False)
                ),
            )
            .filter(
                models.Q(source_widget_count__gt=1) | models.Q(draft_widget_count__gt=1)
            )
            .prefetch_related("nodegroup__cardmodel_set")
        )

        if problems_remain := deduplicate_widgets(nodes_with_excess_widgets):
            raise Exception(
                "Nodes with excess widgets found. Run manage.py validate "
                "(optionally with --verbosity 2) to get a report. This can "
                "be partially fixed by running `manage.py validate --fix 1016`, "
                "but all additional excess widgets must be removed before "
                "proceeding with this migration."
            )

    operations = [
        migrations.RunPython(fail_nicely_if_excess_widgets, migrations.RunPython.noop),
    ]
