"""Tests for keyboard input tools."""

import pytest
from fastmcp import Client


async def test_type_text(client: Client):
    result = await client.call_tool("vnc_type_text", {
        "session_id": "testhost:5900",
        "text": "hello world",
    })
    assert "11 characters" in result.content[0].text


async def test_type_text_empty_raises(client: Client):
    with pytest.raises(Exception, match="empty"):
        await client.call_tool("vnc_type_text", {
            "session_id": "testhost:5900",
            "text": "",
        })


async def test_press_key(client: Client):
    result = await client.call_tool("vnc_press_key", {
        "session_id": "testhost:5900",
        "key": "Return",
    })
    assert "Return" in result.content[0].text


async def test_press_key_alias(client: Client):
    result = await client.call_tool("vnc_press_key", {
        "session_id": "testhost:5900",
        "key": "enter",
    })
    assert "Return" in result.content[0].text


async def test_press_key_escape_alias(client: Client):
    result = await client.call_tool("vnc_press_key", {
        "session_id": "testhost:5900",
        "key": "esc",
    })
    assert "Escape" in result.content[0].text


async def test_key_combo(client: Client):
    result = await client.call_tool("vnc_key_combo", {
        "session_id": "testhost:5900",
        "keys": ["ctrl", "c"],
    })
    assert "Control_L" in result.content[0].text
    assert "c" in result.content[0].text


async def test_key_combo_too_few_raises(client: Client):
    with pytest.raises(Exception, match="at least 2"):
        await client.call_tool("vnc_key_combo", {
            "session_id": "testhost:5900",
            "keys": ["a"],
        })


async def test_press_f_keys(client: Client):
    result = await client.call_tool("vnc_press_key", {
        "session_id": "testhost:5900",
        "key": "f5",
    })
    assert "F5" in result.content[0].text


async def test_type_text_unsupported_char(client: Client):
    """H5: Non-ASCII characters that lack keysym mappings produce ToolError."""
    from mcvnc._state import _state

    session = _state.sessions["testhost:5900"]
    # Make keyboard.write raise KeyError like the real keysymdef lookup would
    session.client.keyboard.write.side_effect = KeyError("\u0301")

    with pytest.raises(Exception, match="Unsupported character"):
        await client.call_tool("vnc_type_text", {
            "session_id": "testhost:5900",
            "text": "caf\u00e9\u0301",
        })

    # Reset side effect for other tests
    session.client.keyboard.write.side_effect = None
