from django.db import migrations, models


def _build_entry(value, name_hint=''):
    if not value:
        return None
    if isinstance(value, dict):
        entry = {}
        entry.update(value)
        # Ensure keys exist
        entry.setdefault('name', name_hint or entry.get('name') or '')
        if 'url' not in entry and 'path' in entry:
            entry['url'] = entry['path']
        elif 'path' not in entry and 'url' in entry:
            entry['path'] = entry['url']
        return entry
    if isinstance(value, str):
        return {
            'name': name_hint or value.split('/')[-1],
            'path': value,
            'url': value,
        }
    return None


def forwards(apps, schema_editor):
    PlateOrder = apps.get_model('printing', 'PlateOrder')
    for obj in PlateOrder.objects.all():
        raw = obj.plate_image
        if not raw:
            obj.plate_image = []
            obj.save(update_fields=['plate_image'])
            continue

        normalized = []
        if isinstance(raw, list):
            for entry in raw:
                built = _build_entry(entry)
                if built:
                    normalized.append(built)
        elif isinstance(raw, dict):
            for key, value in raw.items():
                built = _build_entry(value, name_hint=str(key))
                if built:
                    normalized.append(built)
        else:
            built = _build_entry(raw)
            if built:
                normalized.append(built)

        obj.plate_image = normalized
        obj.save(update_fields=['plate_image'])


class Migration(migrations.Migration):

    dependencies = [
        ('printing', '0018_plateorder_plate_image_to_jsonfield'),
    ]

    operations = [
        migrations.AlterField(
            model_name='plateorder',
            name='plate_image',
            field=models.JSONField(blank=True, default=list, help_text='存储多个开版图片引用信息，例如 [{"file_id": 1, "name": "封面", "path": "/media/xxx"}]', verbose_name='开版图'),
        ),
        migrations.RunPython(forwards, migrations.RunPython.noop),
    ]

