from acl_engine.engine import ACLEngine


def test_executor_blocks_unsafe_file_access(tmp_path) -> None:
    engine = ACLEngine(workspace=tmp_path)

    result = engine.execute('file.read(path="../../etc/passwd") -> data')

    assert result["status"] == "error"
    assert result["error"]["type"] == "ACLSafetyError"


def test_executor_blocks_unsafe_command(tmp_path) -> None:
    engine = ACLEngine(workspace=tmp_path)

    result = engine.execute('system.run(command="rm", args=["-rf", "/"]) -> output')

    assert result["status"] == "error"
    assert result["error"]["type"] == "ACLSafetyError"


def test_executor_standard_policy_blocks_python_subprocess(tmp_path) -> None:
    engine = ACLEngine(workspace=tmp_path)

    result = engine.execute('system.run(command="python", args=["-c", "print(1)"]) -> output')

    assert result["status"] == "error"
    assert result["error"]["code"] == "safety_error"


def test_executor_dev_policy_allows_python_subprocess(tmp_path) -> None:
    engine = ACLEngine(workspace=tmp_path, policy="dev")

    result = engine.execute('system.run(command="python", args=["-c", "print(1)"]) -> output')

    assert result["status"] == "success"
    assert result["data"]["output"]["stdout"].strip() == "1"


def test_executor_can_continue_when_configured(tmp_path) -> None:
    engine = ACLEngine(workspace=tmp_path, stop_on_error=False)
    acl_text = '\n'.join(
        [
            'util.echo(value="first") -> first',
            'system.run(command="rm", args=["-rf", "/"]) -> bad',
            'util.echo(value="second") -> second',
        ]
    )

    result = engine.execute(acl_text)

    assert result["status"] == "error"
    assert result["data"]["first"] == "first"
    assert result["data"]["second"] == "second"
    assert len(result["logs"]) == 3


def test_executor_strict_policy_blocks_delete_and_network(tmp_path) -> None:
    engine = ACLEngine(workspace=tmp_path, policy="strict")
    target = tmp_path / "note.txt"
    target.write_text("hello", encoding="utf-8")

    delete_result = engine.execute('file.delete(path="note.txt")')
    network_result = engine.execute('net.request(method="GET", url="https://example.com") -> response')

    assert delete_result["status"] == "error"
    assert delete_result["error"]["code"] == "safety_error"
    assert network_result["status"] == "error"
    assert network_result["error"]["code"] == "safety_error"
