# Generated by Django 3.2.18 on 2023-04-19 14:52

from django.db import migrations
from wagtail.fields import StreamField

import json

def fix_accordion(obj):
    if isinstance(obj, list):
        for child in obj:
            fix_accordion(child)
    elif isinstance(obj, dict):
        for key, value in obj.items():
            if key == "type" and value == "Accordion":
                obj[key] = "accordion"
            fix_accordion(value)

def forward(apps, schema_editor):
    Page = apps.get_model('wagtailcore', 'Page')
    try:
        for page in Page.objects.all():
            content_type = page.content_type
            page_model_class = apps.get_model(content_type.app_label, content_type.model)
            specific_page = page_model_class.objects.get(id=page.id)

            for field in specific_page._meta.get_fields():
                if isinstance(field, StreamField):
                    raw_data = list(getattr(specific_page, field.name).raw_data)
                    fix_accordion(raw_data)
                    setattr(specific_page, field.name, json.dumps(raw_data))
                    specific_page.save()
    except Exception:
        pass

class Migration(migrations.Migration):

    dependencies = [
        ('roadrunner_bs5', '0002_roadrunnerpage_noindex'),
    ]

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