# Generated by Django 5.2 on 2025-05-08 16:33

from django.db import migrations, models
import json


def convert_input_data_to_json(apps, schema_editor):
    """
    Wrap any plain-text input_data value in a JSON object
    so that it can be safely migrated to a JSONField.

    • If input_data is NULL/empty -> leave unchanged.
    • If input_data already contains valid JSON -> leave unchanged.
    • Otherwise              -> convert "abc"  ➜  {"text_payload": "abc"}
    """
    BrowserUseAgentTask = apps.get_model("api", "BrowserUseAgentTask")

    for task in BrowserUseAgentTask.objects.all().only("id", "input_data").iterator():
        raw = task.input_data
        if not raw:            # None or empty string
            continue

        try:
            # Attempt to load as JSON. If it's already valid JSON (e.g. a dict stored as string, or a JSON string),
            # this will succeed. However, json.loads will fail if `raw` is a simple Python string
            # that is not double-quoted to be a valid JSON string.
            # Example: raw = '{"key": "value"}' -> loads fine
            # Example: raw = '"a simple string"' -> loads fine
            # Example: raw = 'a simple string' -> will raise ValueError
            json.loads(raw)    
            # If `raw` was something like '{"key": "value"}' (a dict stored as text)
            # or '"some json string"' (a JSON string stored as text),
            # it's already compatible or will become compatible with JSONField.
            # No change needed for these cases as JSONField can handle them.
            continue           
        except (TypeError, ValueError, json.JSONDecodeError): # Catch specific JSON errors
            # This means `raw` is likely a plain string like "Fetch this"
            # or some other non-JSON text.
            # We need to wrap it.
            pass

        # If we reached here, `raw` is not valid JSON text. Wrap it.
        task.input_data = json.dumps({"text_payload": raw})
        task.save(update_fields=["input_data"])


class Migration(migrations.Migration):

    dependencies = [
        ('api', '0008_alter_browseruseagenttask_status'),
    ]

    operations = [
        migrations.RunPython(convert_input_data_to_json, migrations.RunPython.noop),
        migrations.AlterField(
            model_name='browseruseagenttask',
            name='input_data',
            field=models.JSONField(blank=True, null=True),
        ),
    ]
