# Generated by Django 3.2.15 on 2022-08-29 16:33

from django.db import migrations, models, transaction

import gi
import logging

gi.require_version("Modulemd", "2.0")
from gi.repository import Modulemd as mmdlib  # noqa: E402


logger = logging.getLogger(__name__)


def populate_new_fields(apps, schema_editor):
    """Populate new fields of modulemd."""
    Modulemd = apps.get_model("rpm", "Modulemd")
    modules_to_update = []

    for modulemd in Modulemd.objects.filter(profiles={}):
        module_index = mmdlib.ModuleIndex.new()
        try:
            ret, err = module_index.update_from_string(modulemd.snippet, False)
            if err:
                raise ValueError(
                    "Repair failed on module "
                    f"'{modulemd.name}.{modulemd.stream}.{modulemd.version}'."
                )
            for module in module_index.get_module_names():
                for stream in module_index.get_module(module).get_all_streams():
                    modulemd.profiles = {}
                    modulemd.description = stream.get_description()
                    for profile in stream.get_profile_names():
                        stream_profile = stream.get_profile(profile)
                        modulemd.profiles[profile] = stream_profile.get_rpms()
                        modules_to_update.append(modulemd)
        except ValueError as err:
            # Due to issue #2735 it could happen that snippet will be empty
            # https://github.com/pulp/pulp_rpm/issues/2735
            logger.warning(
                "Modulemd {}-{}-{} cannot populate new fields."
                "So it will miss the info about profiles and its description.".format(
                    modulemd.name, modulemd.stream, modulemd.version
                )
            )

    Modulemd.objects.bulk_update(modules_to_update, ["profiles", "description"])


class Migration(migrations.Migration):

    dependencies = [
        ("rpm", "0044_noartifact_modules"),
    ]

    operations = [
        migrations.AddField(
            model_name="modulemd",
            name="description",
            field=models.TextField(default="Description"),
            preserve_default=False,
        ),
        migrations.AddField(
            model_name="modulemd",
            name="profiles",
            field=models.JSONField(default=dict),
        ),
        migrations.RunPython(populate_new_fields),
    ]
