# Generated by Django 5.2

from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion


def backfill_persistent_agent_owner(apps, schema_editor):
    """
    Backfill the owner (user) for existing PersistentAgent instances
    from the associated BrowserUseAgent.
    """
    PersistentAgent = apps.get_model('api', 'PersistentAgent')
    for agent in PersistentAgent.objects.filter(user__isnull=True).select_related('browser_use_agent__user'):
        if agent.browser_use_agent and agent.browser_use_agent.user:
            agent.user = agent.browser_use_agent.user
            agent.save(update_fields=['user'])


class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('api', '0050_add_pa_step_agent_ts_idx'),
    ]

    operations = [
        # Add the field as nullable first
        migrations.AddField(
            model_name='persistentagent',
            name='user',
            field=models.ForeignKey(
                null=True, # Temporarily nullable for data migration
                on_delete=django.db.models.deletion.CASCADE,
                related_name='persistent_agents',
                to=settings.AUTH_USER_MODEL
            ),
        ),
        # Backfill the data from the old relationship
        migrations.RunPython(backfill_persistent_agent_owner, migrations.RunPython.noop),
        # Now, make the field non-nullable
        migrations.AlterField(
            model_name='persistentagent',
            name='user',
            field=models.ForeignKey(
                on_delete=django.db.models.deletion.CASCADE,
                related_name='persistent_agents',
                to=settings.AUTH_USER_MODEL
            ),
        ),
        # Finally, add the unique constraint
        migrations.AddConstraint(
            model_name='persistentagent',
            constraint=models.UniqueConstraint(fields=['user', 'name'], name='unique_persistent_agent_user_name'),
        ),
    ] 