from api.services.enhanced_gemini_system import EnhancedLLMSystem


def _tool_call(name: str, arguments: str):
    return {"function": {"name": name, "arguments": arguments}}


def test_enhance_message_history_returns_actual_truncated_count():
    messages = [{"role": "system", "content": "base"}] + [
        {"role": "user", "content": f"u{i}"} for i in range(6)
    ]
    enhanced, truncated = EnhancedLLMSystem.enhance_message_history(messages, max_history=4)
    assert len(enhanced) == 4
    assert truncated == 3
    assert enhanced[0]["role"] == "system"


def test_validate_tool_calls_uses_canonical_json_signatures():
    tool_calls = [
        _tool_call("read", '{"path":"a.py","offset":1}'),
        _tool_call("read", '{"offset":1,"path":"a.py"}'),
    ]
    is_valid, seen = EnhancedLLMSystem.validate_tool_calls_for_loop(tool_calls, seen_tool_calls=[])
    # First call is valid; second is deduped because args are semantically identical.
    assert is_valid is True
    assert len(seen) == 1


def test_detect_potential_loop_uses_tool_call_signatures():
    messages = [
        {
            "role": "assistant",
            "tool_calls": [_tool_call("read", '{"offset":1,"path":"a.py"}')],
        }
    ]
    current = [_tool_call("read", '{"path":"a.py","offset":1}')]
    assert EnhancedLLMSystem.detect_potential_loop(messages, current) is True

