from agent_core.tool_registry import ToolRegistry, run_declared_tools
from agent_core.tools.builtin_tools import calculate_rate, check_required_fields


def test_tool_registry_register_get_and_run():
    registry = ToolRegistry()

    def hello_tool(user_input: str) -> dict:
        return {"echo": user_input}

    registry.register("hello", hello_tool)

    assert registry.get("hello") is hello_tool
    assert registry.run("hello", user_input="demo") == {
        "tool_name": "hello",
        "success": True,
        "arguments": {"user_input": "demo"},
        "result": {"echo": "demo"},
        "error": "",
    }


def test_tool_registry_returns_failed_result_for_missing_tool():
    registry = ToolRegistry()

    result = registry.run("missing", user_input="demo")

    assert result["tool_name"] == "missing"
    assert result["success"] is False
    assert result["error"] == "工具未注册"


def test_run_declared_tools_executes_multiple_tools_in_order():
    results = run_declared_tools(["generate_action_items", "missing_tool"], "请生成行动项")

    assert [item["tool_name"] for item in results] == ["generate_action_items", "missing_tool"]
    assert results[0]["success"] is True
    assert results[1]["success"] is False


def test_calculate_rate_extracts_fraction_like_numbers():
    result = calculate_rate("产线合格率，已完成 18 件，总数 24 件")

    assert result["success"] is True
    assert result["numerator"] == 18.0
    assert result["denominator"] == 24.0
    assert result["rate"] == 0.75


def test_check_required_fields_reports_missing_fields():
    result = check_required_fields("请检查必填项：合同编号、供应商、金额。当前只提供了合同编号和金额。")

    assert "供应商" in result["missing_fields"]
    assert "合同编号" not in result["missing_fields"]
