from django.db import migrations
import random
import string

def forwards(apps, schema_editor):
    User = apps.get_model('accounts', 'User')
    existing = set(User.objects.exclude(unique_code__isnull=True).values_list('unique_code', flat=True))
    def gen():
        return ''.join(random.choices(string.ascii_uppercase, k=4)) + ''.join(random.choices(string.digits, k=8))
    to_update = []
    for u in User.objects.all():
        code = u.unique_code or ''
        need = True
        if code and len(code) == 12 and code[:4].isalpha() and code[:4].upper() == code[:4] and code[4:].isdigit():
            need = False
        if need:
            for _ in range(200):
                newc = gen()
                if newc not in existing:
                    existing.add(newc)
                    u.unique_code = newc
                    to_update.append(u)
                    break
    if to_update:
        User.objects.bulk_update(to_update, ['unique_code'])

def backwards(apps, schema_editor):
    # No-op: keep codes
    pass

class Migration(migrations.Migration):
    dependencies = [
        ('accounts', '0011_alter_user_unique_code'),
    ]
    operations = [
        migrations.RunPython(forwards, backwards),
    ]
