# Generated by Django 5.2.11 on 2026-03-27 17:09

from clinicedc_constants import NOT_APPLICABLE
from django.db import migrations, transaction
from edc_visit_tracking.model_mixins import PreviousVisitError
from edc_visit_tracking.visit_sequence import VisitSequenceError
from tqdm import tqdm

from meta_subject.models import GlucoseFbg


def fix_inconsitent_fasting_columns(apps, schema_editor):  # noqa ARG001
    """
    These rows were incorrectly updated with 8h in migration 0199.

    select count(*) from meta_subject_glucosefbg
    where fasting_duration_estimated='Yes'
    and fasting_duration_str='8h'
    and fasting='No';

    105-20-0253-0 1150 0

    """
    qs = GlucoseFbg.objects.filter(
        fasting_duration_estimated="Yes", fasting_duration_str="8h", fasting="No"
    )

    total = qs.count()
    for obj in tqdm(qs, total=total):
        obj.fasting_duration_estimated = NOT_APPLICABLE
        obj.fasting_duration_str = None
        obj.fasting_duration_delta = None
        with transaction.atomic():
            try:
                obj.save(
                    update_fields=[
                        "fasting_duration_estimated",
                        "fasting_duration_str",
                        "fasting_duration_delta",
                    ]
                )
            except (PreviousVisitError, VisitSequenceError) as e:
                print(e, obj.subject_identifier, obj.visit_code, obj.visit_code_sequence)  # noqa: T201


class Migration(migrations.Migration):
    dependencies = [  # noqa: RUF012
        ("meta_subject", "0245_alter_glucosefbg_options_and_more"),
    ]

    operations = [migrations.RunPython(fix_inconsitent_fasting_columns)]  # noqa: RUF012
