import pytest

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


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


@pytest.mark.parametrize("program,value,expected", [
    ("@text", {"a": 1}, ['{"a":1}']),
    ("@json", "é", ['"é"']),
    ("@html", "!()<>&'\"\t", ["!()&lt;&gt;&amp;&apos;&quot;\t"]),
    ("@uri", "μ", ["%CE%BC"]),
    ("@urid", "%CE%BC", ["μ"]),
    ("@csv", [1, "a\"b", None], ['1,"a""b",']),
    ("@tsv", ["a\tb", "c\n", None], ["a\\tb\tc\\n\t"]),
    ("@sh", ["O'Hara", "x"], ["'O'\\''Hara' 'x'"]),
    ("@base64", "foóbar\n", ["Zm/Ds2Jhcgo="]),
    ("@base64d", "Zm/Ds2Jhcgo=", ["foóbar\n"]),
])
def test_format_filters(program, value, expected):
    assert result(program, value) == expected


def test_formatted_string_keeps_literals_unescaped_and_escapes_interpolation():
    assert result('@uri "https://example.test/?q=\\(.)"', "what is jq?") == [
        "https://example.test/?q=what%20is%20jq%3F"
    ]


def test_format_preserves_interpolation_generator_order():
    assert result('@html "x\\(.[])"', ["<", ">", "&"]) == [
        "x&lt;", "x&gt;", "x&amp;"
    ]


@pytest.mark.parametrize("program,value", [("@csv", "x"), ("@tsv", {}), ("@urid", "%FF"), ("@base64d", "!")])
def test_format_rejects_invalid_input(program, value):
    with pytest.raises(RuntimeError):
        result(program, value)
