"""Helpdesk automation actions — registered in the platform Action Registry.

Imported automatically by ``AutomationConfig.ready()`` via
``autodiscover_modules("automations")``.

These four action specs make helpdesk operations available to the no-code
rule builder so that platform-level ``AutomationRule`` objects can drive
ticket mutations directly.

Event → ticket mapping
----------------------
Each handler reads ``ticket_id`` from ``ctx.trigger_payload``.  All helpdesk
events produced by ``TicketService`` include this key, so the handlers can
load the ticket and call the appropriate service method.
"""

from __future__ import annotations

import structlog

from simorgh.apps.automation.registry import ActionContext, ActionSpec, register_action

_log = structlog.get_logger("simorgh.helpdesk.automations")


# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------

def _load_ticket(ctx: ActionContext):
    """Return the ``Ticket`` instance for *ctx*, or ``None`` if not found."""
    from simorgh.apps.helpdesk.models import Ticket

    ticket_id = ctx.trigger_payload.get("ticket_id")
    if not ticket_id:
        return None
    try:
        return Ticket.objects.select_related("queue", "category", "sla_policy").get(
            pk=ticket_id, tenant_id=ctx.tenant_id
        )
    except Ticket.DoesNotExist:
        _log.warning("helpdesk.automation.ticket_not_found", ticket_id=ticket_id)
        return None


# ---------------------------------------------------------------------------
# Action handlers
# ---------------------------------------------------------------------------

def _handle_assign_to_user(ctx: ActionContext) -> None:
    from simorgh.apps.helpdesk.services import TicketService

    ticket = _load_ticket(ctx)
    if ticket is None:
        return
    user_id = ctx.params.get("user_id")
    if user_id is None:
        return
    TicketService.assign(ticket, assigned_to_id=user_id)


def _handle_set_priority(ctx: ActionContext) -> None:
    ticket = _load_ticket(ctx)
    if ticket is None:
        return
    priority = ctx.params.get("priority")
    if not priority:
        return
    ticket.priority = priority
    ticket.save(update_fields=["priority", "updated_at"])


def _handle_add_tag(ctx: ActionContext) -> None:
    from simorgh.apps.helpdesk.models import Tag, TicketTag

    ticket = _load_ticket(ctx)
    if ticket is None:
        return
    tag_name = ctx.params.get("tag")
    if not tag_name:
        return
    tag = Tag.objects.filter(
        tenant_id=ctx.tenant_id, name=tag_name, is_active=True
    ).first()
    if tag:
        TicketTag.objects.get_or_create(ticket=ticket, tag=tag)


def _handle_change_status(ctx: ActionContext) -> None:
    from simorgh.apps.helpdesk.services import TicketService

    ticket = _load_ticket(ctx)
    if ticket is None:
        return
    new_status = ctx.params.get("status")
    if not new_status:
        return
    TicketService.transition(ticket, new_status=new_status)


# ---------------------------------------------------------------------------
# Registration
# ---------------------------------------------------------------------------

register_action(ActionSpec(
    key="helpdesk.assign_to_user",
    label="Assign Ticket to User",
    module="helpdesk",
    params_schema={
        "type": "object",
        "properties": {
            "user_id": {"type": "integer", "description": "PK of the user to assign to."},
        },
        "required": ["user_id"],
    },
    handler=_handle_assign_to_user,
))

register_action(ActionSpec(
    key="helpdesk.set_priority",
    label="Set Ticket Priority",
    module="helpdesk",
    params_schema={
        "type": "object",
        "properties": {
            "priority": {
                "type": "string",
                "enum": ["low", "normal", "high", "critical"],
                "description": "New priority value.",
            },
        },
        "required": ["priority"],
    },
    handler=_handle_set_priority,
))

register_action(ActionSpec(
    key="helpdesk.add_tag",
    label="Add Tag to Ticket",
    module="helpdesk",
    params_schema={
        "type": "object",
        "properties": {
            "tag": {"type": "string", "description": "Tag name to add."},
        },
        "required": ["tag"],
    },
    handler=_handle_add_tag,
))

register_action(ActionSpec(
    key="helpdesk.change_status",
    label="Change Ticket Status",
    module="helpdesk",
    params_schema={
        "type": "object",
        "properties": {
            "status": {
                "type": "string",
                "description": "New ticket status value.",
            },
        },
        "required": ["status"],
    },
    handler=_handle_change_status,
))
