# Generated by Django migration tooling for TurboVault Engine

from django.db import migrations, models


def populate_sort_order(apps, schema_editor):
    """
    Assign sequential column_sort_order values to existing SatelliteColumn rows.
    Rows within each satellite are ordered by their UUID pk (insertion order proxy)
    and receive sort orders 1, 2, 3, ...
    """
    SatelliteColumn = apps.get_model("engine", "SatelliteColumn")
    # Group columns by satellite
    satellite_ids = (
        SatelliteColumn.objects.values_list("satellite_id", flat=True)
        .distinct()
        .order_by()
    )
    for sat_id in satellite_ids:
        cols = SatelliteColumn.objects.filter(satellite_id=sat_id).order_by(
            "satellite_column_id"
        )
        for idx, col in enumerate(cols, start=1):
            col.column_sort_order = idx
            col.save(update_fields=["column_sort_order"])


class Migration(migrations.Migration):

    dependencies = [
        ("engine", "0006_add_project_directory"),
    ]

    operations = [
        # 1. Add the column as nullable first (safe for existing rows)
        migrations.AddField(
            model_name="satellitecolumn",
            name="column_sort_order",
            field=models.PositiveIntegerField(
                null=True,
                blank=True,
                help_text=(
                    "Display/generation order of this column within the satellite "
                    "(1-based, unique per satellite, auto-assigned on creation)."
                ),
            ),
        ),
        # 2. Populate all existing rows with sequential values per satellite
        migrations.RunPython(populate_sort_order, migrations.RunPython.noop),
        # 3. Now enforce that the field is non-nullable
        migrations.AlterField(
            model_name="satellitecolumn",
            name="column_sort_order",
            field=models.PositiveIntegerField(
                help_text=(
                    "Display/generation order of this column within the satellite "
                    "(1-based, unique per satellite, auto-assigned on creation)."
                ),
            ),
        ),
        # 4. Update ordering meta
        migrations.AlterModelOptions(
            name="satellitecolumn",
            options={"ordering": ["satellite", "column_sort_order"]},
        ),
        # 5. Add unique_together constraint
        migrations.AlterUniqueTogether(
            name="satellitecolumn",
            unique_together={
                ("satellite", "staging_column"),
                ("satellite", "column_sort_order"),
            },
        ),
    ]
