# Generated by Django 4.2.15 on 2024-12-17 10:57

from django.db import migrations, models
from django.db.backends.base.schema import BaseDatabaseSchemaEditor
from django.db.migrations.state import StateApps

from debusine.db.models.work_requests import compute_workflow_runtime_status
from debusine.tasks.models import TaskTypes


def update_workflows_runtime_status(
    apps: StateApps, schema_editor: BaseDatabaseSchemaEditor
) -> None:
    """
    Update WorkRequests workflow_runtime_status field.

    Previously it was using values such as "Running" or "Needs Input" instead of
    "running" or "needs_input".
    """
    WorkRequest = apps.get_model("db", "WorkRequest")

    for work_request in WorkRequest.objects.filter(
        workflow_runtime_status__isnull=False
    ):
        work_request.workflow_runtime_status = (
            work_request.workflow_runtime_status.lower().replace(" ", "_")
        )
        work_request.save()


def revert_update_workflow_runtime_status(
    apps: StateApps, schema_editor: BaseDatabaseSchemaEditor
) -> None:
    """Update WorkRequests workflow_runtime_status field."""
    WorkRequest = apps.get_model("db", "WorkRequest")

    for work_request in WorkRequest.objects.filter(
        workflow_runtime_status__isnull=False
    ):
        work_request.workflow_runtime_status = (
            work_request.workflow_runtime_status.replace("_", " ").title()
        )
        work_request.save()


class Migration(migrations.Migration):
    dependencies = [
        ("db", "0114_user_manager_with_permissions"),
    ]

    operations = [
        migrations.AlterField(
            model_name='workrequest',
            name='workflow_runtime_status',
            field=models.CharField(
                blank=True,
                choices=[
                    ('needs_input', 'Needs Input'),
                    ('running', 'Running'),
                    ('waiting', 'Waiting'),
                    ('pending', 'Pending'),
                    ('aborted', 'Aborted'),
                    ('completed', 'Completed'),
                    ('blocked', 'Blocked'),
                ],
                editable=False,
                max_length=11,
                null=True,
            ),
        ),
        migrations.RunPython(
            update_workflows_runtime_status,
            revert_update_workflow_runtime_status,
        ),
    ]
