"""Shared utilities for building output dicts from key-value pair lists."""

import json
from typing import Any

from pydantic import BaseModel, Field


class KeyValuePair(BaseModel):
    """Single key-value pair definition."""

    key: str = Field(..., description="Field name", min_length=1)
    value: Any = Field(..., description="Value for this field. Use Insert button to reference data from other nodes.")


def build_key_value_output(pairs: list[dict]) -> dict:
    """Build a flat output dict from a list of key-value pair dicts.

    - Validates unique keys (raises ValueError on duplicates)
    - Attempts to parse string values as JSON if they look like objects/arrays
    - Falls back to the raw string if JSON parsing fails
    - Returns the assembled output dict
    """
    # Validate unique keys (defense in depth - UI also validates)
    keys_seen: set[str] = set()
    duplicate_keys: list[str] = []
    for pair in pairs:
        if pair["key"] in keys_seen:
            duplicate_keys.append(pair["key"])
        keys_seen.add(pair["key"])

    if duplicate_keys:
        raise ValueError(
            f"Duplicate keys found: {', '.join(duplicate_keys)}. "
            "Each key must be unique."
        )

    # Build output object
    output_dict: dict[str, Any] = {}
    for pair in pairs:
        value = pair["value"]

        # Try to parse as JSON if it looks like JSON
        if isinstance(value, str) and value.strip().startswith(("{", "[")):
            try:
                value = json.loads(value)
            except (json.JSONDecodeError, ValueError):
                # Not valid JSON, keep as string
                pass

        output_dict[pair["key"]] = value

    return output_dict
