# Generated by Django 4.2.29 on 2026-03-15 11:04

from django.db import migrations


def create_default_team(apps, schema_editor):
    """Create a default team and assign all non-staff users to it."""
    Team = apps.get_model('accounts', 'Team')
    User = apps.get_model('accounts', 'User')
    QuotaConfig = apps.get_model('generation', 'QuotaConfig')

    # Read defaults from QuotaConfig if it exists
    daily_default = 600
    monthly_default = 6000
    try:
        config = QuotaConfig.objects.get(pk=1)
        daily_default = config.default_daily_seconds_limit
        monthly_default = config.default_monthly_seconds_limit
    except QuotaConfig.DoesNotExist:
        pass

    # Calculate total seconds already consumed by non-staff users
    GenerationRecord = apps.get_model('generation', 'GenerationRecord')
    from django.db.models import Sum
    total_used = GenerationRecord.objects.filter(
        user__is_staff=False
    ).aggregate(total=Sum('seconds_consumed'))['total'] or 0

    # Create default team with a generous initial pool
    team = Team.objects.create(
        name='默认团队',
        total_seconds_pool=max(int(total_used) + 36000, 36000),  # used + 10 hours buffer
        total_seconds_used=total_used,
        monthly_seconds_limit=monthly_default,
        daily_member_limit_default=daily_default,
    )

    # Assign all non-staff users to the default team
    User.objects.filter(is_staff=False).update(team=team)


def reverse_migration(apps, schema_editor):
    """Remove default team assignment."""
    User = apps.get_model('accounts', 'User')
    Team = apps.get_model('accounts', 'Team')
    User.objects.filter(team__name='默认团队').update(team=None)
    Team.objects.filter(name='默认团队').delete()


class Migration(migrations.Migration):

    dependencies = [
        ('accounts', '0003_add_team_model_and_user_team_fields'),
        ('generation', '0003_generationrecord_ark_task_id_and_more'),
    ]

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