# Generated by Django 6.0 on 2025-04-02 16:13
from django.apps import apps as django_apps
from django.db import migrations
from django.db.migrations import RunPython
from edc_appointment.constants import MISSED_APPT
from edc_pdutils.dataframes import get_crf
from edc_utils import get_utcnow
from tqdm import tqdm


def update(apps, schema_editor):
    """Correct missed appointments incorrectly set to
    appt_timing=ONTIME_APPT.
    """
    appointment_model_cls = django_apps.get_model("edc_appointment.appointment")
    df_missedvisit = get_crf(
        "meta_subject.subjectvisitmissed",
        subject_visit_model="meta_subject.subjectvisit",
    )
    df_subjects = df_missedvisit[df_missedvisit.appt_timing != MISSED_APPT][
        ["subject_identifier", "visit_code_str", "visit_code_sequence"]
    ].copy()
    for tpl in tqdm(df_subjects.itertuples(), total=len(df_subjects)):
        obj = appointment_model_cls.objects.get(
            subject_identifier=tpl.subject_identifier,
            visit_code=tpl.visit_code_str,
            visit_code_sequence=tpl.visit_code_sequence,
        )
        obj.appt_timing = MISSED_APPT
        obj.modified = get_utcnow()
        obj.user_modified = "erikvw"

        obj.save(update_fields=["appt_timing", "user_modified", "modified"])


class Migration(migrations.Migration):

    dependencies = [
        ("meta_subject", "0220_historicalbloodresultsgludummy_bloodresultsgludummy"),
    ]

    operations = [RunPython(update)]
