"""Tests: execute_command_async terminal delivery via WsDeliveryManager.

Author: Vasiliy Zdanovskiy
email: vasilyvz@gmail.com
"""

from __future__ import annotations

import asyncio
from unittest.mock import AsyncMock, MagicMock, patch

import pytest

from mcp_proxy_adapter.api.handlers_async import execute_command_async


def _make_request_with_manager(ws_id: str = "delivery-ws-id-456"):
    """Request with ws_delivery_manager mock."""
    app = MagicMock()
    manager = MagicMock()
    manager.issue_ws_id.return_value = ws_id
    manager.notify_terminal_delivery = AsyncMock()
    app.state.ws_delivery_manager = manager
    req = MagicMock()
    req.app = app
    req.state = MagicMock()
    return req


@pytest.mark.asyncio
async def test_terminal_goes_to_delivery_manager() -> None:
    """In-process async completion invokes manager.notify_terminal_delivery with issued ws_id."""
    mock_command_class = MagicMock()
    mock_result = MagicMock()
    mock_result.to_dict.return_value = {"ok": True}
    mock_command_class.run = AsyncMock(return_value=mock_result)

    with patch("mcp_proxy_adapter.api.handlers_async.registry") as mock_registry:
        mock_registry.get_command.return_value = mock_command_class
        request = _make_request_with_manager(ws_id="issued-ws-789")
        out = await execute_command_async("echo", {}, None, None, request)
        assert out["ws_id"] == "issued-ws-789"
        await asyncio.sleep(0.1)

        manager = request.app.state.ws_delivery_manager
        manager.notify_terminal_delivery.assert_called_once()
        call_ws_id, call_payload = manager.notify_terminal_delivery.call_args[0]
        assert call_ws_id == "issued-ws-789"
        assert call_payload.get("event") == "delivery_completed"
        assert call_payload.get("ws_id") == "issued-ws-789"
        assert call_payload.get("result") == {"ok": True}
