# Generated by Django 5.2.7 on 2025-10-24 10:04

from django.db import migrations


def convert_user_info_to_array(apps, schema_editor):
    """
    Convert user_info from object format {"key": "value"} to array format
    [{"title": "key", "content": "value"}].
    """
    ControlPlane = apps.get_model("core", "ControlPlane")

    for control_plane in ControlPlane.objects.all():
        if not control_plane.user_info:
            continue

        # If it's already an array (migration already run or new format), skip
        if isinstance(control_plane.user_info, list):
            continue

        # Convert from dict to array
        if isinstance(control_plane.user_info, dict):
            new_user_info = []
            for key, value in control_plane.user_info.items():
                new_user_info.append({"title": key, "content": value})

            control_plane.user_info = new_user_info
            control_plane.save(update_fields=["user_info"])


def reverse_user_info_to_object(apps, schema_editor):
    """
    Reverse the migration by converting array format back to object format.
    Note: help_text will be lost during reversal.
    """
    ControlPlane = apps.get_model("core", "ControlPlane")

    for control_plane in ControlPlane.objects.all():
        if not control_plane.user_info:
            continue

        # If it's already an object, skip
        if isinstance(control_plane.user_info, dict):
            continue

        # Convert from array to dict
        if isinstance(control_plane.user_info, list):
            new_user_info = {}
            for item in control_plane.user_info:
                if isinstance(item, dict) and "title" in item and "content" in item:
                    new_user_info[item["title"]] = item["content"]

            control_plane.user_info = new_user_info
            control_plane.save(update_fields=["user_info"])


class Migration(migrations.Migration):

    dependencies = [
        ("core", "0011_alter_organizationorigin_billing_entity"),
    ]

    operations = [
        migrations.RunPython(convert_user_info_to_array, reverse_user_info_to_object),
    ]
