# Generated by Django 5.2.7 on 2026-05-11 08:56

from django.db import migrations, models
import pydicom


def backfill_series_study_instance_uid(apps, schema_editor):
    Series = apps.get_model('atlas', 'Series')
    SeriesImage = apps.get_model('atlas', 'SeriesImage')

    series_qs = Series.objects.filter(study_instance_uid__isnull=True)

    for series in series_qs.iterator():
        image_obj = (
            SeriesImage.objects.filter(series_id=series.pk, removed=False)
            .exclude(image='')
            .order_by('pk')
            .first()
        )
        if image_obj is None:
            image_obj = (
                SeriesImage.objects.filter(series_id=series.pk)
                .exclude(image='')
                .order_by('pk')
                .first()
            )

        if image_obj is None or not image_obj.image:
            continue

        try:
            with image_obj.image.open('rb') as fp:
                ds = pydicom.dcmread(fp, stop_before_pixels=True, force=True)
            value = ds.get('StudyInstanceUID')
            if value is None:
                continue
            if hasattr(value, 'value'):
                value = value.value
            study_uid = str(value).strip()
            if not study_uid:
                continue

            Series.objects.filter(pk=series.pk).update(study_instance_uid=study_uid)
        except Exception:
            continue


def noop_reverse(apps, schema_editor):
    return


class Migration(migrations.Migration):

    dependencies = [
        ('atlas', '0100_casecollection_show_results_sharing_information'),
    ]

    operations = [
        migrations.AddField(
            model_name='series',
            name='study_instance_uid',
            field=models.CharField(blank=True, db_index=True, max_length=255, null=True),
        ),
        migrations.RunPython(backfill_series_study_instance_uid, noop_reverse),
    ]
