"""Tests for the permission engine."""

from __future__ import annotations

from pathlib import Path

from clients.terminal.tui.permissions import PermissionEngine


def test_default_rules_match_destructive_filesystem() -> None:
    engine = PermissionEngine(store_path=Path("/dev/null"))
    assert engine.check("filesystem", {"action": "delete", "path": "x.txt"}) is not None
    assert engine.check("filesystem", {"action": "read", "path": "x.txt"}) is None


def test_default_rules_match_terminal_rm() -> None:
    engine = PermissionEngine(store_path=Path("/dev/null"))
    assert engine.check("terminal", {"command": "rm -rf /tmp/x"}) is not None
    assert engine.check("terminal", {"command": "ls /tmp"}) is None


def test_default_rules_match_code_exec_and_ssh_exec() -> None:
    engine = PermissionEngine(store_path=Path("/dev/null"))
    assert engine.check("code_exec", {"language": "python", "code": "print(1)"}) is not None
    assert engine.check("ssh_exec", {"host": "server", "command": "uptime"}) is not None


def test_default_rules_match_shell_command() -> None:
    engine = PermissionEngine(store_path=Path("/dev/null"))
    assert engine.check("shell", {"action": "run", "command": "ls"}) is not None


def test_always_allow_bypasses_confirmation(tmp_path: Path) -> None:
    store = tmp_path / "permissions.json"
    engine = PermissionEngine(store_path=store)
    engine.set_always_allow("terminal", {"command": "rm -rf /tmp/x"})
    assert engine.check("terminal", {"command": "rm -rf /tmp/x"}) is None


def test_always_deny_is_detected_without_rule(tmp_path: Path) -> None:
    store = tmp_path / "permissions.json"
    engine = PermissionEngine(store_path=store)
    engine.set_always_deny("terminal", {"command": "rm -rf /tmp/x"})
    assert engine.is_always_deny("terminal", {"command": "rm -rf /tmp/x"}) is True
    assert engine.check("terminal", {"command": "rm -rf /tmp/x"}) is None


def test_extract_target_for_tools() -> None:
    engine = PermissionEngine(store_path=Path("/dev/null"))
    assert engine.extract_target("filesystem", {"path": "/tmp/x"}) == "/tmp/x"
    assert engine.extract_target("filesystem", {"destination": "/tmp/y"}) == "/tmp/y"
    assert engine.extract_target("terminal", {"command": "ls"}) == "ls"
    assert engine.extract_target("ssh_exec", {"host": "h1"}) == "h1"
