from typing import Any

from pydantic import BaseModel

from service_forge.workflow.node import Node
from service_forge.workflow.port import Port


class UpdateObjectNode(Node):
    DEFAULT_INPUT_PORTS = [
        Port("object", Any),
        Port("fields", tuple[str, Any], is_extended=True),
    ]

    DEFAULT_OUTPUT_PORTS = [
        Port("object", Any),
    ]

    def __init__(self, name: str) -> None:
        super().__init__(name)

    def _run(
        self,
        object: Any,
        fields: list[tuple[int, tuple[str, Any]]],
    ) -> Any:
        if isinstance(object, BaseModel):
            updates = {f[0]: f[1] for _, f in fields}
            object = object.model_copy(update=updates)
        else:
            for _, f in fields:
                object[f[0]] = f[1]
    
        self.activate_output_edges("object", object)
