"""Data migration: helpdesk.Automation → automation.AutomationRule.

Converts all existing ``helpdesk.Automation`` rows into
``automation.AutomationRule`` rows so they are executed by the
platform Automation Engine instead of the now-deprecated
``helpdesk.AutomationEngine``.

Trigger mapping
---------------
helpdesk trigger         platform event name
------------------------  -----------------------------------
ticket_created            helpdesk.ticket.created
ticket_updated            helpdesk.ticket.updated
ticket_status_changed     helpdesk.ticket.status_changed
reply_added               helpdesk.reply.added
time_elapsed              (skipped — no equivalent event)

Action conversion
-----------------
Old format: ``{"type": "assign_to_user", "user_id": 42, …}``
New format: ``{"action": "helpdesk.assign_to_user", "params": {"user_id": 42}}``
"""

from __future__ import annotations

from django.db import migrations

# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------

_TRIGGER_EVENT_MAP: dict[str, str] = {
    "ticket_created": "helpdesk.ticket.created",
    "ticket_updated": "helpdesk.ticket.updated",
    "ticket_status_changed": "helpdesk.ticket.status_changed",
    "reply_added": "helpdesk.reply.added",
}

_ACTION_KEY_MAP: dict[str, str] = {
    "assign_to_user": "helpdesk.assign_to_user",
    "set_priority": "helpdesk.set_priority",
    "add_tag": "helpdesk.add_tag",
    "change_status": "helpdesk.change_status",
}

# Legacy action fields to lift into ``params``.
_EXTRA_PARAM_FIELDS: dict[str, list[str]] = {
    "assign_to_user": ["user_id"],
    "set_priority": ["priority"],
    "add_tag": ["tag"],
    "change_status": ["status"],
}


def _convert_action(action: dict) -> dict | None:
    action_type = action.get("type", "")
    new_key = _ACTION_KEY_MAP.get(action_type)
    if new_key is None:
        return None  # unknown / unsupported action type
    params = {}
    for field in _EXTRA_PARAM_FIELDS.get(action_type, []):
        if field in action:
            params[field] = action[field]
    return {"action": new_key, "params": params}


def _migrate_forward(apps, schema_editor):
    Automation = apps.get_model("helpdesk", "Automation")
    AutomationRule = apps.get_model("automation", "AutomationRule")
    OrganizationNode = apps.get_model("organizations", "OrganizationNode")

    migrated = 0
    skipped = 0

    for automation in Automation.objects.select_related("tenant").iterator():
        event_name = _TRIGGER_EVENT_MAP.get(automation.trigger)
        if event_name is None:
            # time_elapsed or unknown — cannot map to an event-driven rule.
            skipped += 1
            continue

        # Resolve an organization node for the owning tenant.
        node = OrganizationNode.objects.filter(tenant=automation.tenant).first()
        if node is None:
            skipped += 1
            continue

        # Convert actions list.
        new_actions = []
        for action in (automation.actions or []):
            converted = _convert_action(action)
            if converted is not None:
                new_actions.append(converted)

        AutomationRule.objects.create(
            tenant=automation.tenant,
            organization_node=node,
            name=f"[Migrated] {automation.name}",
            description=automation.description or "",
            is_active=automation.is_active,
            trigger_type="event",
            trigger_event=event_name,
            conditions=automation.conditions or [],
            actions=new_actions,
        )
        migrated += 1


def _migrate_backward(apps, schema_editor):
    # Remove only the rows we created (identified by "[Migrated]" prefix).
    AutomationRule = apps.get_model("automation", "AutomationRule")
    AutomationRule.objects.filter(name__startswith="[Migrated] ").delete()


class Migration(migrations.Migration):

    dependencies = [
        ("helpdesk", "0003_ticket_reference_number"),
        ("automation", "0003_webhook_endpoint_delivery"),
        ("organizations", "0001_initial"),
    ]

    operations = [
        migrations.RunPython(_migrate_forward, reverse_code=_migrate_backward),
    ]
