"""tool_args_coerce：模型传入 JSON 字符串时的解析。"""

from __future__ import annotations

import pytest

from aicd.agent.tool_args_coerce import (
    coerce_tool_json_array,
    coerce_tool_json_block_object,
    coerce_tool_json_object,
)


def test_coerce_array_string() -> None:
    r = coerce_tool_json_array('["a", "b"]', "x", allow_empty=True)
    assert r == ["a", "b"]


def test_coerce_array_empty_forbidden() -> None:
    r = coerce_tool_json_array([], "x", allow_empty=False)
    assert isinstance(r, dict) and r["ok"] is False


def test_coerce_array_none_required() -> None:
    r = coerce_tool_json_array(None, "x", allow_empty=True)
    assert isinstance(r, dict) and "required" in r["error"]


def test_coerce_object_string() -> None:
    obj, err = coerce_tool_json_object('{"a": 1}', "p")
    assert err is None and obj == {"a": 1}


def test_coerce_object_none() -> None:
    obj, err = coerce_tool_json_object(None, "p")
    assert err is None and obj == {}


def test_coerce_block_object_string() -> None:
    blk, berr = coerce_tool_json_block_object(
        '{"type":"paragraph","text":"hi"}', "blocks", 0
    )
    assert berr is None
    assert blk["type"] == "paragraph"


@pytest.mark.parametrize(
    "bad",
    [123, object()],
)
def test_coerce_array_rejects_non_string_list(bad: object) -> None:
    r = coerce_tool_json_array(bad, "x", allow_empty=True)
    assert isinstance(r, dict) and r["ok"] is False
