"""Clipboard tools."""

from fastmcp import Context
from fastmcp.exceptions import ToolError

from mcvnc._state import get_state, mcp


@mcp.tool()
async def vnc_get_clipboard(ctx: Context, session_id: str) -> str:
    """Read the remote desktop's clipboard text.

    Note: The clipboard is updated when the VNC server sends clipboard data.
    Some servers only send clipboard updates on certain events.

    Args:
        session_id: VNC session.
    """
    state = get_state(ctx)
    session = state.get(session_id)

    async with session.lock:
        text = session.client.clipboard.text

    if not text:
        return "Clipboard is empty (or server hasn't sent clipboard data yet)"
    return text


@mcp.tool()
async def vnc_set_clipboard(ctx: Context, session_id: str, text: str) -> str:
    """Send text to the remote desktop's clipboard.

    The text is encoded as latin-1 per the RFB protocol spec, so only
    Latin-1 characters are supported.

    Args:
        session_id: VNC session.
        text: Text to send to the remote clipboard.
    """
    state = get_state(ctx)
    session = state.get(session_id)

    try:
        text.encode("latin-1")
    except UnicodeEncodeError as e:
        raise ToolError(
            f"Clipboard text contains characters outside latin-1: {e}. "
            f"The VNC RFB protocol only supports latin-1 encoded text."
        )

    async with session.lock:
        session.client.clipboard.write(text)
        await session.client.drain()

    return f"Sent {len(text)} characters to remote clipboard"
