# Generated by Django 5.2.14 on 2026-05-18 12:06

import io
import os

from PIL import Image
from tqdm import tqdm

from time import sleep

from django.db import migrations
from django.core.files.base import ContentFile
from django.core.files.storage import default_storage


def update_image_attachments(apps, schema_editor):
    """Update existing attachments to ensure that image attachments have thumbnails.
    
    For each existing attachment, check if it is an image.
    If it is, generate a thumbnail for it.

    Note: This function mirrors the logic used in the Attachment model's
    check_is_image method, at the time of writing this migration (2026-05-18).
    """

    import common.tasks

    Attachment = apps.get_model('common', 'Attachment')

    # Find all Attachment instances which (potentially) have a file attached
    attachments = Attachment.objects.exclude(attachment__isnull=True).exclude(attachment='')

    if attachments.count() == 0:
        return

    progress = tqdm(total=attachments.count(), desc='Migration common.0043: Updating attachments')

    for attachment in attachments:
        progress.update(1)
        
        if not attachment.attachment:
            continue
        
        if not attachment.attachment.name or not default_storage.exists(attachment.attachment.name):
            continue

        common.tasks.rebuild_attachment(attachment.pk)


class Migration(migrations.Migration):

    dependencies = [
        ("common", "0042_attachment_is_image_attachment_thumbnail"),
    ]

    operations = [
        migrations.RunPython(update_image_attachments, reverse_code=migrations.RunPython.noop),
    ]
