# Generated by Django 5.0.8 on 2024-09-19 15:59

import json
import pickle
import uuid

from django.db import migrations, models


def reverse_remove_bigint_id(apps, schema_editor):
    Conversation = apps.get_model("database", "Conversation")
    index = 1
    for conversation in Conversation.objects.all():
        conversation.id = index
        conversation.save()
        index += 1


def update_conversation_id_in_job_state(apps, schema_editor):
    try:
        DjangoJob = apps.get_model("django_apscheduler", "DjangoJob")
        Conversation = apps.get_model("database", "Conversation")

        for job in DjangoJob.objects.all():
            job_state = pickle.loads(job.job_state)
            kwargs = job_state.get("kwargs")
            conversation_id = kwargs.get("conversation_id") if kwargs else None
            automation_metadata = json.loads(job_state.get("name", "{}"))

            if not conversation_id:
                job.delete()

            if conversation_id:
                try:
                    conversation = Conversation.objects.get(id=conversation_id)
                    automation_metadata["conversation_id"] = str(conversation.temp_id)
                    name = json.dumps(automation_metadata)
                    job_state["name"] = name
                    job_state["kwargs"]["conversation_id"] = str(conversation.temp_id)
                    job.job_state = pickle.dumps(job_state)
                    job.save()
                except Conversation.DoesNotExist:
                    pass
    except LookupError:
        pass


def no_op(apps, schema_editor):
    pass


def disable_triggers(apps, schema_editor):
    schema_editor.execute('ALTER TABLE "database_conversation" DISABLE TRIGGER ALL;')


def enable_triggers(apps, schema_editor):
    schema_editor.execute('ALTER TABLE "database_conversation" ENABLE TRIGGER ALL;')


class Migration(migrations.Migration):
    dependencies = [
        ("database", "0063_conversation_temp_id"),
    ]

    operations = [
        migrations.RunPython(no_op, reverse_code=enable_triggers),
        migrations.RunPython(update_conversation_id_in_job_state, reverse_code=no_op),
        migrations.RemoveField(
            model_name="conversation",
            name="id",
        ),
        migrations.RenameField(
            model_name="conversation",
            old_name="temp_id",
            new_name="id",
        ),
        migrations.AlterField(
            model_name="conversation",
            name="id",
            field=models.UUIDField(
                db_index=True, default=uuid.uuid4, editable=False, primary_key=True, serialize=False, unique=True
            ),
        ),
        migrations.RunPython(no_op, reverse_code=reverse_remove_bigint_id),
        migrations.RunPython(no_op, reverse_code=disable_triggers),
    ]
