# Generated manually for adding content ForeignKey to Images model

from django.db import migrations, models
import django.db.models.deletion


def migrate_task_to_content(apps, schema_editor):
    """Migrate existing Images to use content instead of task"""
    Images = apps.get_model('writer', 'Images')
    Content = apps.get_model('writer', 'Content')
    
    # Update images that have a task with a content_record
    for image in Images.objects.filter(task__isnull=False, content__isnull=True):
        try:
            # Try to get content via task.content_record
            task = image.task
            if task:
                try:
                    content = Content.objects.get(task=task)
                    image.content = content
                    image.save(update_fields=['content'])
                except Content.DoesNotExist:
                    # If content doesn't exist, leave content as null
                    pass
        except Exception:
            # If any error occurs, leave content as null
            pass


class Migration(migrations.Migration):

    dependencies = [
        ('writer', '0006_update_status_choices'),
    ]

    operations = [
        # Make task field nullable first
        migrations.AlterField(
            model_name='images',
            name='task',
            field=models.ForeignKey(
                blank=True,
                help_text='The task this image belongs to (legacy, use content instead)',
                null=True,
                on_delete=django.db.models.deletion.CASCADE,
                related_name='images',
                to='writer.tasks'
            ),
        ),
        # Add content field
        migrations.AddField(
            model_name='images',
            name='content',
            field=models.ForeignKey(
                blank=True,
                help_text='The content this image belongs to (preferred)',
                null=True,
                on_delete=django.db.models.deletion.CASCADE,
                related_name='images',
                to='writer.content'
            ),
        ),
        # Update ordering
        migrations.AlterModelOptions(
            name='images',
            options={'ordering': ['content', 'position', '-created_at'], 'verbose_name': 'Image', 'verbose_name_plural': 'Images'},
        ),
        # Add new indexes
        migrations.AddIndex(
            model_name='images',
            index=models.Index(fields=['content', 'image_type'], name='igny8_image_content_image_type_idx'),
        ),
        migrations.AddIndex(
            model_name='images',
            index=models.Index(fields=['content', 'position'], name='igny8_image_content_position_idx'),
        ),
        # Data migration: populate content field from task.content_record
        migrations.RunPython(
            code=migrate_task_to_content,
            reverse_code=migrations.RunPython.noop,
        ),
    ]

