from django.db import migrations


def create_rtc_bot(apps, schema_editor):
    Bot = apps.get_model('aiapp', 'Bot')
    if not Bot.objects.filter(name='RTC_Voice_Agent').exists():
        # 手动指定一个不会冲突的 id
        from django.db import connection
        with connection.cursor() as cursor:
            cursor.execute("SELECT COALESCE(MAX(id), 0) + 1 FROM aiapp_bot")
            next_id = cursor.fetchone()[0]
        Bot.objects.create(
            id=next_id,
            name='RTC_Voice_Agent',
            description='RTC实时语音智能体'
        )


def remove_rtc_bot(apps, schema_editor):
    Bot = apps.get_model('aiapp', 'Bot')
    Bot.objects.filter(name='RTC_Voice_Agent').delete()


class Migration(migrations.Migration):

    dependencies = [
        ('aiapp', '0002_initial'),
    ]

    operations = [
        migrations.RunPython(create_rtc_bot, remove_rtc_bot),
    ]
