"""Tests for the inline permission dialog."""

from __future__ import annotations

import pytest

from clients.terminal.tui.screens.permission_dialog import PermissionDialogScreen
from clients.terminal.tui.events import WsEvent
from clients.terminal.tui.tui_app import NaviCodeTui


@pytest.mark.anyio
async def test_tool_started_triggers_permission_dialog() -> None:
    """A destructive tool_started event opens the permission dialog."""
    async with NaviCodeTui(new_session=True).run_test() as pilot:
        await pilot.pause()
        chat = pilot.app.query_one("ChatPanel")
        assert chat is not None
        pilot.app.post_message(WsEvent({"type": "tool_started", "tool": "filesystem", "args": {"action": "delete", "path": "/tmp/x"}}))
        await pilot.pause()
        assert pilot.app.screen_stack[-1].__class__.__name__ == "PermissionDialogScreen"


@pytest.mark.anyio
async def test_allow_once_passes_tool_to_chat() -> None:
    async with NaviCodeTui(new_session=True).run_test() as pilot:
        await pilot.pause()
        chat = pilot.app.query_one("ChatPanel")
        assert chat is not None
        pilot.app.post_message(WsEvent({"type": "tool_started", "tool": "filesystem", "args": {"action": "delete", "path": "/tmp/x"}}))
        await pilot.pause()
        dialog = pilot.app.screen_stack[-1]
        assert isinstance(dialog, PermissionDialogScreen)
        await pilot.click("#allow_once")
        await pilot.pause()
        assert any(item.kind == "tool_started" for item in chat._model.items)


@pytest.mark.anyio
async def test_deny_once_adds_synthetic_tool_call() -> None:
    async with NaviCodeTui(new_session=True).run_test() as pilot:
        await pilot.pause()
        chat = pilot.app.query_one("ChatPanel")
        assert chat is not None
        pilot.app.post_message(WsEvent({"type": "tool_started", "tool": "filesystem", "args": {"action": "delete", "path": "/tmp/x"}}))
        await pilot.pause()
        dialog = pilot.app.screen_stack[-1]
        assert isinstance(dialog, PermissionDialogScreen)
        await pilot.click("#deny_once")
        await pilot.pause()
        assert any(item.kind == "tool_call" for item in chat._model.items)
