"""Tests for source_map.lookup_line parent-pointer fallback."""

from valn8n_lib.source_map import lookup_line

# Synthetic source map simulating a real workflow file
SOURCE_MAP: dict[str, int] = {
    "": 1,
    "/name": 2,
    "/nodes": 3,
    "/nodes/0": 4,
    "/nodes/0/name": 5,
    "/nodes/0/type": 6,
    "/nodes/1": 20,
    "/nodes/1/name": 21,
    "/nodes/1/type": 22,
    "/nodes/1/parameters": 23,
    "/nodes/1/parameters/url": 24,
    "/settings": 50,
}


class TestLookupLineExactMatch:
    def test_exact_match(self) -> None:
        assert lookup_line(SOURCE_MAP, "/nodes/0/name") == 5

    def test_exact_match_root(self) -> None:
        assert lookup_line(SOURCE_MAP, "") == 1

    def test_exact_match_nested(self) -> None:
        assert lookup_line(SOURCE_MAP, "/nodes/1/parameters/url") == 24


class TestLookupLineFallback:
    def test_one_level_fallback(self) -> None:
        # /nodes/0/credentials missing → falls back to /nodes/0
        assert lookup_line(SOURCE_MAP, "/nodes/0/credentials") == 4

    def test_one_level_fallback_notes(self) -> None:
        # /nodes/1/notes missing → falls back to /nodes/1
        assert lookup_line(SOURCE_MAP, "/nodes/1/notes") == 20

    def test_multi_level_fallback(self) -> None:
        # /nodes/0/parameters/deep/nested → /nodes/0 (no /nodes/0/parameters)
        assert lookup_line(SOURCE_MAP, "/nodes/0/parameters/deep/nested") == 4

    def test_root_fallback_description(self) -> None:
        # /description missing, no intermediate match → root
        assert lookup_line(SOURCE_MAP, "/description") == 1

    def test_root_fallback_deep(self) -> None:
        # /missing/deep/path → root
        assert lookup_line(SOURCE_MAP, "/missing/deep/path") == 1


class TestLookupLineEdgeCases:
    def test_none_source_map(self) -> None:
        assert lookup_line(None, "/nodes/0") is None

    def test_empty_source_map(self) -> None:
        assert lookup_line({}, "/nodes/0") is None

    def test_empty_source_map_root_present(self) -> None:
        assert lookup_line({"": 1}, "/anything") == 1
