"""
Data migration: merge furniture category into decoration.

For each CardTemplate with category='furniture':
1. Create a DecorationAttributes record from FurnitureAttributes data
2. Change the template's category to 'decoration'
"""
from django.db import migrations


def merge_furniture_into_decoration(apps, schema_editor):
    CardTemplate = apps.get_model('card', 'CardTemplate')
    FurnitureAttributes = apps.get_model('card', 'FurnitureAttributes')
    DecorationAttributes = apps.get_model('card', 'DecorationAttributes')

    furniture_templates = CardTemplate.objects.filter(category='furniture')

    for template in furniture_templates:
        # Get existing furniture attributes if any
        try:
            fa = FurnitureAttributes.objects.get(template=template)
            # Create decoration attributes from furniture data
            DecorationAttributes.objects.create(
                template=template,
                decoration_type=fa.furniture_type,
                style=fa.style,
                material=fa.material,
                size=fa.dimensions,  # dimensions -> size
                placement='',
                indoor_outdoor='室内',
                installation_required=fa.assembly_required,
                care_instructions=fa.care_instructions,
            )
            # Delete old furniture attributes
            fa.delete()
        except FurnitureAttributes.DoesNotExist:
            # No furniture attrs, just create empty decoration attrs
            DecorationAttributes.objects.create(template=template)

        # Change category
        template.category = 'decoration'
        template.save(update_fields=['category'])

    # Also update any Card records that reference furniture category
    Card = apps.get_model('card', 'Card')
    Card.objects.filter(category='furniture').update(category='decoration')

    # Also update any CardBatch records
    CardBatch = apps.get_model('card', 'CardBatch')
    CardBatch.objects.filter(category='furniture').update(category='decoration')


def reverse_migration(apps, schema_editor):
    # Cannot reliably reverse this migration
    pass


class Migration(migrations.Migration):

    dependencies = [
        ('card', '0012_decoration_furniture_optional_fields'),
    ]

    operations = [
        migrations.RunPython(merge_furniture_into_decoration, reverse_migration),
    ]
