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", [
    ('startswith("é")', "élan", [True]),
    ('endswith("an")', "élan", [True]),
    ('ltrimstr("foo")', "foobar", ["bar"]),
    ('rtrimstr("bar")', "foobar", ["foo"]),
    ('trimstr("foo")', "foobarfoo", ["bar"]),
    ('trim', " \u00a0abc\u3000 ", ["abc"]),
    ('ascii_downcase', "AéZ", ["aéz"]),
    ('join(",")', ["a", 1, True, None, False], ["a,1,true,,false"]),
    ('indices("o")', "🇬🇧oo", [[2, 3]]),
    ('split("")', "é中", [["é", "中"]]),
])
def test_string_builtin(program, value, expected):
    assert result(program, value) == expected


def test_string_builtin_type_error_is_runtime_error():
    with pytest.raises(RuntimeError):
        result('startswith("x")', 1)


def test_regex_match_reports_codepoint_offsets_and_named_captures():
    matches = result('match("(?<word>é+)")', "xéé")[0]
    assert matches["offset"] == 1
    assert matches["length"] == 2
    assert matches["captures"] == [{"offset": 1, "length": 2, "string": "éé", "name": "word"}]


def test_regex_global_scan_and_case_insensitive_test():
    assert result('scan("a+"; "gi")', "Aaa ba")[0] == "Aaa"
    assert result('test("foo"; "i")', "FOO") == [True]


def test_regex_capture_and_substitution_use_named_captures():
    assert result('capture("(?<a>[a-z]+)-(?<n>[0-9]+)")', "xyz-14") == [{"a": "xyz", "n": "14"}]
    assert result('gsub("(?<x>.)"; "+\\(.x)-")', "ab") == ["+a-+b-"]


def test_regex_replacement_stream_preserves_multiple_outputs():
    assert result('gsub("p"; "a", "b")', "p") == ["a", "b"]


def test_runtime_string_description_matches_jq_utf8_truncation_boundary():
    assert result('try -. catch .', "xxxx☆☆☆☆☆☆☆☆") == [
        'string ("xxxx☆☆☆☆☆☆...") cannot be negated'
    ]
