import pytest

from jq_interpreter.errors import RuntimeError
from jq_interpreter.evaluator import evaluate
from jq_interpreter.parser import parse


def results(program, value):
    return list(evaluate(parse(program), value))


def test_path_tracks_composed_indexes_in_generator_order():
    assert results("path(.foo[0,1])", {"foo": [10, 20]}) == [["foo", 0], ["foo", 1]]


def test_path_root_and_paths_exclude_root():
    value = [1, [[], {"a": 2}]]
    assert results("path(.)", value) == [[]]
    assert results("paths", value) == [[0], [1], [1, 0], [1, 1], [1, 1, "a"]]


def test_getpath_reads_existing_and_missing_locations():
    value = {"foo": ["a", "b"]}
    assert results('getpath(["foo",1])', value) == ["b"]
    assert results('getpath(["foo",9])', value) == [None]


def test_pick_reconstructs_the_selected_path_with_null_leaf():
    assert results("pick(.a.b.c)", {"a": {"b": {"c": None}}}) == [
        {"a": {"b": {"c": None}}}
    ]


@pytest.mark.parametrize("program", ["getpath(1)", "path(.foo | 1)"])
def test_path_apis_reject_invalid_accesses(program):
    with pytest.raises(RuntimeError):
        results(program, {"foo": 1})
