# Generated by Django 4.1.2 on 2023-07-20 00:42

from django.db import migrations
from django.db.models import Q


def get_history(history):
    """
    Return a list of mappings of all history entries from oldest to newest as:
        {"timestamp": "<YYYY-MM-DD-HH:MM:SS>", "message": "message"}
    """
    entries = (entry.partition(' ') for entry in history.strip().splitlines(False))
    return [{"timestamp": ts, "message": message} for ts, _, message in entries]


def convert_history(apps, schema_editor):
    Package = apps.get_model("packagedb", "Package")

    # Filter for Packages with history
    packages_with_history = (
        Package.objects.filter(Q(history__isnull=False) | ~Q(history=""))
        .iterator(chunk_size=5000)
    )

    unupdated = []
    for i, package in enumerate(packages_with_history):
        if  i > 0 and not i % 5000:
            Package.objects.bulk_update(
                objs=unupdated,
                fields=[
                    "history_json",
                ]
            )
            unupdated = []
        package.history_json = get_history(package.history)
        unupdated.append(package)

    if unupdated:
        Package.objects.bulk_update(
            objs=unupdated,
            fields=[
                "history_json",
            ]
        )


class Migration(migrations.Migration):
    dependencies = [
        ("packagedb", "0073_package_history_json"),
    ]

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