# Generated by Django 4.2 on 2024-01-01 00:00

import uuid
from django.db import migrations, models


def convert_session_ids_to_uuid(apps, schema_editor):
    """Convert existing session_id values to UUIDs."""
    ChatSession = apps.get_model("django_chain", "ChatSession")

    for session in ChatSession.objects.all():
        # Try to parse existing session_id as UUID, if it fails, generate a new one
        try:
            # Check if it's already a valid UUID
            uuid.UUID(str(session.session_id))
        except (ValueError, TypeError):
            # If not a valid UUID, generate a new one
            session.session_id = str(uuid.uuid4())
            session.save(update_fields=["session_id"])


def reverse_convert_session_ids(apps, schema_editor):
    """Reverse migration - convert UUIDs back to strings (no-op since CharField can hold UUID strings)."""
    # No action needed as CharField can hold UUID string representations
    pass


class Migration(migrations.Migration):
    dependencies = [
        ("django_chain", "0001_initial"),
    ]

    operations = [
        # First, ensure all session_id values are valid UUID strings
        migrations.RunPython(
            convert_session_ids_to_uuid,
            reverse_convert_session_ids,
        ),
        # Then alter the field to UUIDField
        migrations.AlterField(
            model_name="chatsession",
            name="session_id",
            field=models.UUIDField(
                default=uuid.uuid4,
                editable=False,
                help_text="Unique UUID identifier for this chat session",
                unique=True,
            ),
        ),
    ]
