from django.db import migrations


def backfill_uuids(apps, schema_editor):
    Scrobble = apps.get_model("scrobbles", "Scrobble")
    from uuid import uuid4

    scrobbles = Scrobble.objects.filter(uuid__isnull=True)
    # Process in batches to avoid loading all into memory
    while scrobbles.exists():
        batch = list(scrobbles[:1000])
        for s in batch:
            s.uuid = uuid4()
        Scrobble.objects.bulk_update(batch, ["uuid"], batch_size=1000)


class Migration(migrations.Migration):

    dependencies = [
        ("scrobbles", "0103_scrobble_species_observation_and_more"),
    ]

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