#!/usr/bin/env python3
"""
Unit tests for automation2 graphUtils - resolveParameterReferences (ref/value format).
"""

import pytest

from modules.workflows.automation2.graphUtils import resolveParameterReferences


class TestResolveParameterReferences:
    """Test structured ref/value resolution."""

    def test_ref_simple(self):
        node_outputs = {
            "n1": {"payload": {"country": "CH"}},
        }
        value = {"type": "ref", "nodeId": "n1", "path": ["payload", "country"]}
        assert resolveParameterReferences(value, node_outputs) == "CH"

    def test_ref_root(self):
        node_outputs = {"n1": {"a": 1, "b": 2}}
        value = {"type": "ref", "nodeId": "n1", "path": []}
        assert resolveParameterReferences(value, node_outputs) == {"a": 1, "b": 2}

    def test_ref_nested(self):
        node_outputs = {"form_1": {"customer": {"country": "DE", "name": "Test"}}}
        value = {"type": "ref", "nodeId": "form_1", "path": ["customer", "country"]}
        assert resolveParameterReferences(value, node_outputs) == "DE"

    def test_ref_array_index(self):
        node_outputs = {"n1": {"items": ["a", "b", "c"]}}
        value = {"type": "ref", "nodeId": "n1", "path": ["items", 1]}
        assert resolveParameterReferences(value, node_outputs) == "b"

    def test_ref_missing_node(self):
        node_outputs = {}
        value = {"type": "ref", "nodeId": "missing", "path": ["x"]}
        assert resolveParameterReferences(value, node_outputs) == value

    def test_value_wrapper(self):
        value = {"type": "value", "value": "static text"}
        assert resolveParameterReferences(value, {}) == "static text"

    def test_value_nested_ref(self):
        node_outputs = {"n1": {"x": 42}}
        value = {"type": "value", "value": {"type": "ref", "nodeId": "n1", "path": ["x"]}}
        assert resolveParameterReferences(value, node_outputs) == 42

    def test_dict_mixed_ref_value(self):
        node_outputs = {"n1": {"result": "hello"}}
        value = {
            "prompt": {"type": "ref", "nodeId": "n1", "path": ["result"]},
            "suffix": {"type": "value", "value": " world"},
        }
        result = resolveParameterReferences(value, node_outputs)
        assert result == {"prompt": "hello", "suffix": " world"}

    def test_legacy_string_template(self):
        node_outputs = {"n1": {"country": "CH"}}
        value = "Land: {{n1.country}}"
        assert resolveParameterReferences(value, node_outputs) == "Land: CH"
