# Generated migration to clean up deprecated fields
from django.db import migrations, models


def migrate_deprecated_data(apps, schema_editor):
    """Migrate data from deprecated fields to new unified structure"""
    Tasks = apps.get_model('writer', 'Tasks')
    Content = apps.get_model('writer', 'Content')
    
    # Migrate Tasks: ensure entity_type and cluster_role have defaults
    for task in Tasks.objects.all():
        changed = False
        if not task.entity_type:
            task.entity_type = 'post'
            changed = True
        if not task.cluster_role:
            task.cluster_role = 'hub'
            changed = True
        if changed:
            task.save()
    
    # Migrate Content: ensure entity_type is set from task if available
    for content in Content.objects.select_related('task').all():
        changed = False
        if content.task and content.task.entity_type and not content.entity_type:
            content.entity_type = content.task.entity_type
            changed = True
        if content.task and content.task.cluster_role and not content.cluster_role:
            content.cluster_role = content.task.cluster_role
            changed = True
        if not content.entity_type:
            content.entity_type = 'post'
            changed = True
        if changed:
            content.save()


class Migration(migrations.Migration):

    dependencies = [
        ('writer', '0005_phase3_mark_deprecated_fields'),
        ('planner', '0003_cleanup_remove_deprecated_fields'),
    ]

    operations = [
        # Step 1: Migrate data
        migrations.RunPython(migrate_deprecated_data, migrations.RunPython.noop),
        
        # Step 2: Remove deprecated fields from Tasks
        migrations.RemoveField(
            model_name='tasks',
            name='content_structure',
        ),
        migrations.RemoveField(
            model_name='tasks',
            name='content_type',
        ),
        migrations.RemoveField(
            model_name='tasks',
            name='content',
        ),
        migrations.RemoveField(
            model_name='tasks',
            name='word_count',
        ),
        migrations.RemoveField(
            model_name='tasks',
            name='meta_title',
        ),
        migrations.RemoveField(
            model_name='tasks',
            name='meta_description',
        ),
        migrations.RemoveField(
            model_name='tasks',
            name='assigned_post_id',
        ),
        migrations.RemoveField(
            model_name='tasks',
            name='post_url',
        ),
        
        # Step 4: Remove deprecated fields from Content
        migrations.RemoveField(
            model_name='content',
            name='categories',
        ),
        migrations.RemoveField(
            model_name='content',
            name='tags',
        ),
    ]

