"""Tests for approval policy normalization and HITL decisions."""

from ieum.approval_policy import (
    APPROVAL_POLICY_FULL_TRUSTED,
    APPROVAL_POLICY_MANUAL,
    APPROVAL_POLICY_READ_ONLY,
    APPROVAL_POLICY_SAFE_WRITE,
    decide_actions,
    is_valid_approval_policy,
    normalize_approval_policy,
)


def test_normalize_aliases() -> None:
    assert normalize_approval_policy("manual") == APPROVAL_POLICY_MANUAL
    assert normalize_approval_policy("read-only") == APPROVAL_POLICY_READ_ONLY
    assert normalize_approval_policy("readonly") == APPROVAL_POLICY_READ_ONLY
    assert normalize_approval_policy("safe-write") == APPROVAL_POLICY_SAFE_WRITE
    assert normalize_approval_policy("trusted") == APPROVAL_POLICY_FULL_TRUSTED


def test_normalize_unknown_uses_default() -> None:
    assert normalize_approval_policy("unknown") == APPROVAL_POLICY_MANUAL
    assert normalize_approval_policy("unknown", default="safe_write") == APPROVAL_POLICY_SAFE_WRITE


def test_is_valid_approval_policy() -> None:
    assert is_valid_approval_policy("manual")
    assert is_valid_approval_policy("readonly")
    assert is_valid_approval_policy("trusted")
    assert not is_valid_approval_policy("nope")


def test_manual_policy_returns_none() -> None:
    decisions = decide_actions(
        APPROVAL_POLICY_MANUAL,
        [{"action": {"tool": "write_file"}}],
    )
    assert decisions is None


def test_read_only_policy_allows_fetch_only() -> None:
    decisions = decide_actions(
        APPROVAL_POLICY_READ_ONLY,
        [
            {"action": {"tool": "fetch_url"}},
            {"action": {"tool": "write_file"}},
        ],
    )
    assert decisions is not None
    assert [d.decision for d in decisions] == ["approve", "reject"]


def test_safe_write_policy_blocks_shell_like_tools() -> None:
    decisions = decide_actions(
        APPROVAL_POLICY_SAFE_WRITE,
        [
            {"action": {"tool": "write_file"}},
            {"action": {"tool": "python_repl"}},
        ],
    )
    assert decisions is not None
    assert [d.decision for d in decisions] == ["approve", "reject"]


def test_full_trusted_approves_all() -> None:
    decisions = decide_actions(
        APPROVAL_POLICY_FULL_TRUSTED,
        [
            {"action": {"tool": "write_file"}},
            {"action": {"tool": "python_repl"}},
        ],
    )
    assert decisions is not None
    assert all(d.decision == "approve" for d in decisions)
