from soniclue_basekit import CliFormatter


def test_empty_formatter():
    fmt = CliFormatter()
    assert fmt.as_cmd_list() == []
    assert str(fmt) == ""


def test_cmd_only():
    assert CliFormatter("cmd").as_cmd_list() == ["cmd"]


def test_set_cmd_returns_self_and_updates():
    fmt = CliFormatter("old")
    result = fmt.set_cmd("new")
    assert result is fmt
    assert fmt.as_cmd_list() == ["new"]


def test_clear_returns_self_and_removes_pairs():
    fmt = CliFormatter("cmd").add("--a", "1").add("--b", "2")
    result = fmt.clear()
    assert result is fmt
    assert fmt.as_cmd_list() == ["cmd"]


def test_add_returns_self():
    fmt = CliFormatter("cmd")
    assert fmt.add("--k", "v") is fmt


def test_chaining():
    result = CliFormatter("cmd").add("--a", "1").add("--b", "2").as_cmd_list()
    assert result == ["cmd", "--a", "1", "--b", "2"]


def test_add_none_is_noop():
    fmt = CliFormatter("cmd")
    fmt.add("--k", None)
    assert fmt.as_cmd_list() == ["cmd"]


def test_add_empty_string_bare_flag():
    assert CliFormatter("cmd").add("--verbose", "").as_cmd_list() == ["cmd", "--verbose"]


def test_string_value_roundtrip():
    fmt = CliFormatter("cmd").add("--k", "value")
    assert fmt.as_cmd_list() == ["cmd", "--k", "value"]


def test_value_with_spaces_roundtrip():
    fmt = CliFormatter("cmd").add("--k", "hello world")
    assert fmt.as_cmd_list() == ["cmd", "--k", "hello world"]


def test_integer_value():
    fmt = CliFormatter("cmd").add("--n", 42)
    assert fmt.as_cmd_list() == ["cmd", "--n", "42"]


def test_custom_to_str():
    fmt = CliFormatter("cmd", to_str=str).add("--k", "v")
    assert str(fmt) == "cmd --k v"


def test_list_value_comma_delimiter():
    fmt = CliFormatter("cmd", multi_value_delimiter=",").add("--k", ["v1", "v2"])
    assert fmt.as_cmd_list() == ["cmd", "--k", "v1,v2"]


def test_key_prefix():
    fmt = CliFormatter("cmd", key_prefix="--").add("key", "val")
    assert fmt.as_cmd_list() == ["cmd", "--key", "val"]


def test_equals_kv_delimiter():
    fmt = CliFormatter("cmd", key_value_delimiter="=").add("--k", "v")
    assert fmt.as_cmd_list() == ["cmd", "--k=v"]
    assert str(fmt) == "cmd --k=v"


def test_spec_example_1():
    fmt = CliFormatter("my_script.sh").add("--key", "value")
    assert fmt.as_cmd_list() == ["my_script.sh", "--key", "value"]
    assert str(fmt) == "my_script.sh --key value"


def test_spec_example_2():
    fmt = CliFormatter(
        "my_script.sh",
        key_prefix="--",
        key_value_delimiter="=",
        multi_value_delimiter=",",
        to_str=str,
    ).add("key", ["v1", "v2"])
    assert fmt.as_cmd_list() == ["my_script.sh", "--key=v1,v2"]
    assert str(fmt) == "my_script.sh --key=v1,v2"
