# retoor <retoor@molodetz.nl>

import asyncio

from tests.conftest import run_async
from devplacepy.services.devii.interaction.broker import InteractionBroker


def test_broker_site_prompt_returns_submitted_values():
    async def wait_site(interaction_id, frame, timeout):
        assert frame["title"] == "Deploy?"
        assert frame["widgets"][0]["type"] == "confirm"
        return {
            "status": "submitted",
            "interaction_id": interaction_id,
            "values": {"delete": True},
        }

    broker = InteractionBroker("main", wait_site=wait_site)

    async def run():
        return await broker.prompt(
            {
                "title": "Deploy?",
                "widgets": [
                    {
                        "type": "confirm",
                        "name": "delete",
                        "label": "Delete",
                        "default": False,
                    }
                ],
            }
        )

    result = run_async(run())
    assert result.status == "submitted"
    assert result.values == {"delete": True}
    assert result.meta["adapter"] == "site-chat"
    assert result.meta["degraded"] is False
    assert broker.open_id() is None


def test_broker_plain_adapter_parses_reply():
    async def present_plain(menu: str) -> str:
        assert "yes" in menu.lower() or "Delete" in menu
        return "yes"

    broker = InteractionBroker("cli", present_plain=present_plain)
    result = run_async(
        broker.prompt(
            {
                "title": "Delete?",
                "widgets": [
                    {"type": "confirm", "name": "ok", "label": "OK", "default": False}
                ],
            }
        )
    )
    assert result.status == "submitted"
    assert result.values == {"ok": True}
    assert result.meta["degraded"] is True


def test_broker_invalid_args_raise():
    from devplacepy.services.devii.errors import ToolInputError

    broker = InteractionBroker("main")
    try:
        run_async(broker.prompt({"title": "x", "widgets": []}))
        assert False, "expected ToolInputError"
    except ToolInputError:
        pass


def test_broker_timeout_status():
    async def wait_site(interaction_id, frame, timeout):
        raise asyncio.TimeoutError()

    broker = InteractionBroker("main", wait_site=wait_site)
    result = run_async(
        broker.prompt(
            {
                "title": "T?",
                "timeout_sec": 1,
                "widgets": [
                    {"type": "confirm", "name": "ok", "label": "OK"}
                ],
            }
        )
    )
    assert result.status == "timeout"
    assert result.values == {}
