"""MCP resources for VNC sessions."""

import asyncio
import json

from fastmcp import Context
from fastmcp.exceptions import ToolError

from mcvnc._screen import _rgba_to_png
from mcvnc._state import SCREENSHOT_MAX_WIDTH, SCREENSHOT_TIMEOUT, get_state, mcp


@mcp.resource("vnc://sessions")
async def sessions_resource(ctx: Context) -> str:
    """List all active VNC sessions as JSON."""
    state = get_state(ctx)
    sessions = []
    for sid, s in state.sessions.items():
        sessions.append({
            "session_id": sid,
            "host": s.host,
            "port": s.port,
            "width": s.width,
            "height": s.height,
        })
    return json.dumps(sessions)


@mcp.resource("vnc://sessions/{session_id}/screen", mime_type="image/png")
async def screen_resource(ctx: Context, session_id: str) -> bytes:
    """Capture a screenshot as a PNG image resource."""
    state = get_state(ctx)
    session = state.get(session_id)

    async with session.lock:
        try:
            pixels = await asyncio.wait_for(
                session.client.screenshot(), timeout=SCREENSHOT_TIMEOUT
            )
        except asyncio.TimeoutError:
            raise ToolError(
                f"Screenshot timed out after {SCREENSHOT_TIMEOUT}s. "
                f"The VNC server may be unresponsive."
            )

        session.width = session.client.video.width
        session.height = session.client.video.height

    return _rgba_to_png(pixels, SCREENSHOT_MAX_WIDTH)
