# Generated by Django 4.2.20 on 2025-09-27 14:19

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


def populate_initial_user_message(apps, schema_editor):
    """
    Populate the initial_user_message field for existing ToolCall records.
    Since migration 0011 cleared all ToolCall records, this should only run
    if there are any remaining records in production.
    """
    ToolCall = apps.get_model('unicom', 'ToolCall')
    Message = apps.get_model('unicom', 'Message')

    for tool_call in ToolCall.objects.all():
        try:
            # Get the tool_call_message that this ToolCall represents
            tool_call_msg = tool_call.tool_call_message

            # Find the initial user message by traversing back through the request chain
            # The tool_call_message belongs to a request, find the initial request
            request = tool_call_msg.request
            initial_request = request.initial_request or request

            # The initial user message is the message of the initial request
            if initial_request.message:
                tool_call.initial_user_message = initial_request.message
                tool_call.save(update_fields=['initial_user_message'])
            else:
                # If we can't find a proper initial message, delete this orphaned ToolCall
                tool_call.delete()

        except Exception as e:
            # If there's any issue finding the message, delete the orphaned ToolCall
            # These are task queue records, safe to delete
            tool_call.delete()


def reverse_populate_initial_user_message(apps, schema_editor):
    """
    Reverse operation - set initial_user_message to null
    """
    ToolCall = apps.get_model('unicom', 'ToolCall')
    ToolCall.objects.update(initial_user_message=None)


class Migration(migrations.Migration):

    dependencies = [
        ('unicom', '0011_toolcall_add_message_reference'),
    ]

    operations = [
        migrations.AddField(
            model_name='message',
            name='response_to_tool_call',
            field=models.ForeignKey(blank=True, help_text='The ToolCall that this message is responding to (for assistant messages from tool responses)', null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='response_messages', to='unicom.toolcall'),
        ),
        # First add the field as nullable
        migrations.AddField(
            model_name='toolcall',
            name='initial_user_message',
            field=models.ForeignKey(blank=True, null=True, help_text='The original user message that this tool call is responding to', on_delete=django.db.models.deletion.CASCADE, related_name='triggered_tool_calls', to='unicom.message'),
        ),
        # Populate the field with correct values
        migrations.RunPython(
            populate_initial_user_message,
            reverse_code=reverse_populate_initial_user_message,
        ),
        # Make the field non-nullable
        migrations.AlterField(
            model_name='toolcall',
            name='initial_user_message',
            field=models.ForeignKey(help_text='The original user message that this tool call is responding to', on_delete=django.db.models.deletion.CASCADE, related_name='triggered_tool_calls', to='unicom.message'),
        ),
    ]
