from django.db import migrations


def convert_page_data_to_dict(apps, schema_editor):
    Scrobble = apps.get_model("scrobbles", "Scrobble")
    for scrobble in Scrobble.objects.filter(media_type="Book").exclude(
        log__page_data=None
    ):
        page_data = scrobble.log.get("page_data")
        if isinstance(page_data, list):
            new_page_data = {}
            for entry in page_data:
                page_num = entry.get("page_number")
                if page_num is not None:
                    try:
                        page_num = int(page_num)
                    except (ValueError, TypeError):
                        continue
                    new_page_data[page_num] = entry
            scrobble.log["page_data"] = new_page_data
            scrobble.save(update_fields=["log"])


class Migration(migrations.Migration):

    dependencies = [
        ("scrobbles", "0095_backfill_null_visibility"),
    ]

    operations = [
        migrations.RunPython(
            convert_page_data_to_dict,
            reverse_code=migrations.RunPython.noop,
        ),
    ]
