# Backfill: create the default "House" agent, give every existing user a
# numeric 6-digit UID + a unique referral code, and group agentless users under
# House — so the "every user is under an agent" rule holds for old accounts too.
import random
import string

from django.db import migrations


def _unique_uid(Profile, Agent):
    while True:
        uid = str(random.randint(100000, 999999))
        if (not Profile.objects.filter(uid=uid).exists()
                and not Agent.objects.filter(uid=uid).exists()):
            return uid


def _unique_code(Profile, Agent):
    chars = string.ascii_uppercase + string.digits
    while True:
        code = ''.join(random.choices(chars, k=6))
        if (not Profile.objects.filter(referral_code=code).exists()
                and not Agent.objects.filter(referral_code=code).exists()):
            return code


def forwards(apps, schema_editor):
    Profile = apps.get_model('main', 'Profile')
    Agent = apps.get_model('main', 'Agent')

    house = Agent.objects.filter(name='House').first()
    if house is None:
        house = Agent.objects.create(
            name='House',
            uid=_unique_uid(Profile, Agent),
            referral_code=_unique_code(Profile, Agent),
            is_active=True,
        )

    for profile in Profile.objects.all():
        changed = []
        # Convert non-numeric / wrong-length UIDs to a random 6-digit number.
        if not (profile.uid and profile.uid.isdigit() and len(profile.uid) == 6):
            profile.uid = _unique_uid(Profile, Agent)
            changed.append('uid')
        if not profile.referral_code:
            profile.referral_code = _unique_code(Profile, Agent)
            changed.append('referral_code')
        if profile.agent_id is None:
            profile.agent = house
            changed.append('agent')
        if changed:
            profile.save(update_fields=changed)


def backwards(apps, schema_editor):
    # Non-destructive: leave generated UIDs/codes/agent links in place.
    pass


class Migration(migrations.Migration):

    dependencies = [
        ('main', '0013_agent_profile_last_ip_profile_last_seen_and_more'),
    ]

    operations = [
        migrations.RunPython(forwards, backwards),
    ]
