# Generated by Django 4.2.19 on 2025-03-31 12:28

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


def fill_stored_event_count(apps, schema_editor):
    Issue = apps.get_model("issues", "Issue")

    lookup_dict = {
        d["id"]: d["count"]
        for d in Issue.objects.values("id").annotate(count=models.Count("event"))}

    for issue in Issue.objects.all():
        correct_value = lookup_dict.get(issue.id, 0)
        if issue.stored_event_count != correct_value:
            print("Updating event count for issue %s from %d to %d" % (issue, issue.stored_event_count, correct_value))
            issue.stored_event_count = correct_value
            issue.save()

    # Note: because "irrelevances" have been calculated based on stored_event_count, those will be wrong too... but
    # there doesn't seem to be an easy way to recover from that, so we'll just let the problem fix itself over time.
    # easy meaning: both easy-enough to write a datamigration for, and not super-expensive to run.


class Migration(migrations.Migration):

    dependencies = [
        ("issues", "0012_alter_issue_calculated_type_and_more"),
        # ("events", ... no need: since issues.0009_fill_stored_event_count is implied b/c we depend on issues.0012, we
        # _know_ we can do the things we need to do.
    ]

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