"""P1-09 数据迁移：把 ParadiseUser.favorability 写到该用户主设备 UserDevice.favorability

迁移策略：
    1. 遍历所有 favorability > 0 的用户
    2. 找该用户的主设备（is_primary=True），无主设备则取最近绑定的设备
    3. 写入 UserDevice.favorability
    4. 用户没有任何设备绑定 → 跳过（数据保留在 ParadiseUser，等用户首次绑定时由
       业务层处理）

幂等性：
    重复执行不会重复写入（按 favorability=10 默认值判断，已迁移过的设备值非默认
    或已被业务层覆盖时不再重写）。

注意：
    1. 旧的 ParadiseUser.favorability 字段保留不删，由后续版本统一清理
    2. AffinitySetting 单例和默认 8 条规则、5 个等级由 management command
       (seed_affinity, P1-10) 处理，不在数据迁移中
"""

from django.db import migrations


def migrate_favorability_forward(apps, schema_editor):
    ParadiseUser = apps.get_model('userapp', 'ParadiseUser')
    UserDevice = apps.get_model('device_interaction', 'UserDevice')

    migrated_count = 0
    skipped_no_device = 0
    skipped_zero = 0

    for user in ParadiseUser.objects.iterator():
        favorability = getattr(user, 'favorability', 0) or 0
        if favorability <= 0:
            skipped_zero += 1
            continue

        # 优先取主设备，没有就取最近绑定的设备
        primary = (
            UserDevice.objects
            .filter(user_id=user.id, is_primary=True)
            .order_by('-bound_at')
            .first()
        )
        target = primary or (
            UserDevice.objects
            .filter(user_id=user.id)
            .order_by('-bound_at')
            .first()
        )
        if target is None:
            skipped_no_device += 1
            continue

        # 仅当目标值仍是默认值（10）时写入，避免覆盖业务层后续修改
        if target.favorability == 10:
            target.favorability = favorability
            target.save(update_fields=['favorability'])
            migrated_count += 1

    print(
        f"\n[P1-09] favorability 数据迁移完成："
        f"成功 {migrated_count}，无设备跳过 {skipped_no_device}，"
        f"零值跳过 {skipped_zero}"
    )


def migrate_favorability_backward(apps, schema_editor):
    """回滚：把 UserDevice.favorability 写回 ParadiseUser.favorability（取主设备值）"""
    ParadiseUser = apps.get_model('userapp', 'ParadiseUser')
    UserDevice = apps.get_model('device_interaction', 'UserDevice')

    rolled_back = 0
    for user in ParadiseUser.objects.iterator():
        primary = (
            UserDevice.objects
            .filter(user_id=user.id, is_primary=True)
            .order_by('-bound_at')
            .first()
        )
        if primary and primary.favorability != 10:
            user.favorability = primary.favorability
            user.save(update_fields=['favorability'])
            rolled_back += 1

    print(f"\n[P1-09 rollback] 回滚 favorability {rolled_back} 条到 ParadiseUser")


class Migration(migrations.Migration):

    dependencies = [
        ('userapp', '0005_affinitysetting_affinitylevel_is_deleted_and_more'),
        ('device_interaction', '0003_userdevice_affinity_level_userdevice_favorability_and_more'),
    ]

    operations = [
        migrations.RunPython(
            migrate_favorability_forward,
            migrate_favorability_backward,
        ),
    ]
