"""Set Values node for defining multiple key-value pairs."""

from typing import Any

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

from fw_nodes_core.utils.key_value_builder import KeyValuePair, build_key_value_output


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


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

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


class SetValuesNode(BaseNode):
    """Define multiple key-value pairs that other nodes can reference."""

    input_schema = SetValuesInput
    output_schema = SetValuesOutput

    metadata = NodeMetadata(
        name="Set Values",
        description="Define multiple key-value pairs that other nodes can reference",
        category="data",
        icon="📦",
        color="#795548",
    )

    async def execute_logic(
        self,
        validated_inputs: dict[str, Any],
        context: NodeExecutionContext,
    ) -> SetValuesOutput:
        """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 SetValuesOutput(**output_dict)
