# retoor <retoor@molodetz.nl>

import json
from devplacepy.services.devii.agentic.loop import _run_tool_call
from tests.conftest import run_async
class _FakeDispatcher:
    def __init__(self):
        self.calls = []

    async def dispatch(self, name, arguments):
        self.calls.append((name, arguments))
        return json.dumps({"status": "ok"})
def _run(call, dispatcher=None):
    return json.loads(run_async(_run_tool_call(dispatcher, call)))


def test_truncated_arguments_reported_not_dispatched():
    dispatcher = _FakeDispatcher()
    call = {
        "function": {
            "name": "project_write_file",
            "arguments": '{"path":"a.md","content":"# hi',
        }
    }
    out = _run(call, dispatcher)
    assert out["error"] == "tool_input_truncated"
    assert "one write tool call per turn" in out["message"]
    assert dispatcher.calls == []


def test_non_object_arguments_rejected():
    dispatcher = _FakeDispatcher()
    out = _run({"function": {"name": "x", "arguments": '"a string"'}}, dispatcher)
    assert out["error"] == "tool_input_error"
    assert dispatcher.calls == []


def test_valid_string_arguments_dispatched():
    dispatcher = _FakeDispatcher()
    out = _run({"function": {"name": "vote", "arguments": '{"value":1}'}}, dispatcher)
    assert out["status"] == "ok"
    assert dispatcher.calls == [("vote", {"value": 1})]


def test_valid_dict_arguments_dispatched():
    dispatcher = _FakeDispatcher()
    out = _run({"function": {"name": "vote", "arguments": {"value": -1}}}, dispatcher)
    assert out["status"] == "ok"
    assert dispatcher.calls == [("vote", {"value": -1})]


def test_missing_arguments_defaults_to_empty_object():
    dispatcher = _FakeDispatcher()
    out = _run({"function": {"name": "auth_status"}}, dispatcher)
    assert out["status"] == "ok"
    assert dispatcher.calls == [("auth_status", {})]
