# Generated by Django 5.2.11 on 2026-03-17 01:57
import sys

from django.db import migrations
from django.db.models import Count
from tqdm import tqdm

from clinicedc_constants import NULL_STRING
from edc_qareports.models import Note
from django.apps import apps as django_apps


def update_note_models(apps, schema_editor):
    sys.stdout.write("Updating visit_code on Note model...\n")
    for report_models in (
            Note.objects.values("report_model").annotate(total=Count("id")).order_by()
    ):
        print(report_models.get("report_model"))
        model_cls = django_apps.get_model(report_models.get("report_model"))
        report_query = model_cls.objects.exclude(visit_code__isnull=True)
        for report_obj in tqdm(report_query, total=report_query.count()):
            try:
                note_obj = Note.objects.get(
                    report_model=model_cls._meta.label_lower,
                    subject_identifier=report_obj.subject_identifier,
                    visit_code=NULL_STRING,
                )
            except Note.DoesNotExist:
                pass
            else:
                note_obj.visit_code = report_obj.visit_code or NULL_STRING
                note_obj.visit_code_sequence = report_obj.visit_code_sequence or 0
                note_obj.save()

    sys.stdout.write("Done.\n")


class Migration(migrations.Migration):

    dependencies = [
        (
            "edc_qareports",
            "0023_remove_note_edc_qareports_note_report_model_subj_uniq_and_more",
         ),
        ("meta_reports", "0080_auto_20260317_0437"),
    ]

    operations = [migrations.RunPython(update_note_models)]
