# Generated by Django 5.2 on 2025-06-30 14:16

from django.db import migrations
import logging

logger = logging.getLogger(__name__)


def cleanup_orphaned_browser_agents(apps, schema_editor):
    """
    Remove BrowserUseAgent instances that don't have an associated PersistentAgent.
    """
    BrowserUseAgent = apps.get_model('api', 'BrowserUseAgent')
    PersistentAgent = apps.get_model('api', 'PersistentAgent')
    
    # Find orphaned BrowserUseAgent instances
    # These are browser agents that don't have a corresponding PersistentAgent
    browser_agents_with_persistent = PersistentAgent.objects.values_list('browser_use_agent_id', flat=True)
    orphaned_browser_agents = BrowserUseAgent.objects.exclude(id__in=browser_agents_with_persistent)
    
    orphaned_count = orphaned_browser_agents.count()
    
    if orphaned_count > 0:
        logger.info(f"Found {orphaned_count} orphaned BrowserUseAgent instances to clean up")
        
        # Log the orphaned agents for debugging
        for agent in orphaned_browser_agents:
            logger.info(f"Deleting orphaned BrowserUseAgent: {agent.id} (name: {agent.name}, user: {agent.user_id})")
        
        # Delete the orphaned agents
        orphaned_browser_agents.delete()
        logger.info(f"Successfully cleaned up {orphaned_count} orphaned BrowserUseAgent instances")
    else:
        logger.info("No orphaned BrowserUseAgent instances found")


def reverse_cleanup_orphaned_browser_agents(apps, schema_editor):
    """
    This migration is irreversible since we can't restore deleted data.
    """
    pass


class Migration(migrations.Migration):

    dependencies = [
        ('api', '0053_alter_persistentagentcommsendpoint_owner_agent_and_more'),
    ]

    operations = [
        migrations.RunPython(
            cleanup_orphaned_browser_agents,
            reverse_cleanup_orphaned_browser_agents,
        ),
    ]
