"""Return node for returning values to calling workflow."""

from typing import Any

from flowire_sdk import BaseNode, BaseNodeOutput, HandleConfig, NodeExecutionContext, NodeHandles, NodeMetadata
from pydantic import BaseModel, ConfigDict, Field

from fw_nodes_core.utils.key_value_builder import KeyValuePair, build_key_value_output


class ReturnInput(BaseModel):
    """Input schema with list of key-value pairs."""
    pairs: list[KeyValuePair] = Field(
        default_factory=list,
        description="Key-value pairs to return to caller",
    )


class ReturnOutput(BaseNodeOutput):
    """Output schema with dynamic fields from user-defined keys."""

    model_config = ConfigDict(extra="allow")  # Allow arbitrary fields from key-value pairs


class ReturnNode(BaseNode):
    """Return values to the calling workflow (Call Flow or For Each)."""

    input_schema = ReturnInput
    output_schema = ReturnOutput

    metadata = NodeMetadata(
        name="Return",
        description="Return values to the calling workflow (Call Flow or For Each)",
        category="logic",
        icon="↩️",
        color="#FF5722",
        handles=NodeHandles(
            inputs=[HandleConfig(id="default", position="left")],
            outputs=[],  # Terminal node - no outputs
        ),
    )

    async def execute_logic(
        self,
        validated_inputs: dict[str, Any],
        context: NodeExecutionContext,
    ) -> ReturnOutput:
        """Build output object from key-value pairs.

        - Validates unique keys
        - Attempts to parse values as JSON (objects/arrays)
        - Falls back to string if JSON parsing fails
        - Returns flat object with all key-value pairs
        """
        pairs = validated_inputs.get("pairs", [])
        output_dict = build_key_value_output(pairs)
        return ReturnOutput(**output_dict)
