# Generated by Django 3.2.13 on 2023-07-11 03:02

from django.db import migrations, models


def forward(apps, schema_editor):
    Rule = apps.get_model("promgen", "Rule")
    Label = apps.get_model("promgen", "RuleLabel")
    Annotation = apps.get_model("promgen", "RuleAnnotation")

    # For our forward migration, we want to loop through all the old Label and Annotation entries
    # and convert them to a dictionary property on our Rule model
    for rule in Rule.objects.all():
        rule.labels = {l.name: l.value for l in Label.objects.filter(rule_id=rule.id)}
        rule.annotations = {l.name: l.value for l in Annotation.objects.filter(rule_id=rule.id)}
        rule.save()


def reverse(apps, schema_editor):
    Rule = apps.get_model("promgen", "Rule")
    Label = apps.get_model("promgen", "RuleLabel")
    Annotation = apps.get_model("promgen", "RuleAnnotation")
    for rule in Rule.objects.all():
        Label.objects.bulk_create(
            [Label(rule_id=rule.id, name=x, value=rule.labels[x]) for x in rule.labels]
        )
        Annotation.objects.bulk_create(
            [Annotation(rule_id=rule.id, name=x, value=rule.annotations[x]) for x in rule.annotations]
        )


class Migration(migrations.Migration):

    dependencies = [
        ("promgen", "0021_shard_load"),
    ]

    operations = [
        migrations.AddField(
            model_name="rule",
            name="annotations",
            field=models.JSONField(default=dict),
        ),
        migrations.AddField(
            model_name="rule",
            name="labels",
            field=models.JSONField(default=dict),
        ),
        migrations.RunPython(forward, reverse),
        migrations.DeleteModel(
            name="RuleAnnotation",
        ),
        migrations.DeleteModel(
            name="RuleLabel",
        ),
    ]
