"""
{{ display_name }} - Respond node.

This module generates the response for the webhook caller.
"""

from datetime import datetime, timezone

from torivers_sdk.automation.output import JsonDataBlock, build_output_data

from state import {{ class_name }}State


async def respond(state: {{ class_name }}State) -> dict:
    """Generate response for the webhook caller.

    Args:
        state: Current handler state.

    Returns:
        Dictionary with state updates including response data.
    """
    context = state["context"]

    context.log_progress("Responding", "Generating webhook response")

    # Build response based on processing status
    if not state.get("is_valid", False):
        response = {
            "status": "error",
            "code": 400,
            "message": "Validation failed",
            "errors": state.get("validation_errors", []),
        }
    elif state.get("processed", False):
        response = {
            "status": "success",
            "code": 200,
            "message": "Event processed successfully",
            "event_id": state.get("event_id"),
            "actions": state.get("actions_taken", []),
        }
    else:
        response = {
            "status": "error",
            "code": 500,
            "message": "Processing failed",
            "event_id": state.get("event_id"),
        }

    context.log_success("Response generated", f"Status: {response['status']}")

    return {
        "current_step": "completed",
        "response": response,
        "output_data": build_output_data(
            JsonDataBlock(
                label="Webhook Response",
                data={
                    "processed": state.get("processed", False),
                    "event_id": state.get("event_id"),
                    "actions_taken": state.get("actions_taken", []),
                    "response": response,
                },
                display_hint="key_value",
            ),
        ),
        "metadata": {
            "completed_at": datetime.now(timezone.utc).isoformat(),
        },
    }
