"""Blaxel end-to-end tests — mirrors blaxel.e2e.test.ts.

Uses shared sandbox with installStrategy='running'.
Reduced test set (no .env deny in passthrough mode).
"""

from __future__ import annotations

import time

import pytest

from tests.e2e.conftest import skip_no_blaxel

from agentsh_secure_sandbox import SecureConfig, SecuredSandbox, secure_sandbox
from agentsh_secure_sandbox.adapters import blaxel

pytestmark = [pytest.mark.e2e, pytest.mark.timeout(300), skip_no_blaxel]

# ─── Module-scoped setup / teardown ────────────────────────


@pytest.fixture(scope="module")
async def secured() -> SecuredSandbox:  # type: ignore[misc]
    from blaxel_core import SandboxInstance  # type: ignore[import-untyped]

    # Use existing sandbox with agentsh pre-installed and running.
    raw = await SandboxInstance.get("agentsh-blaxel")
    adapter = blaxel(raw)
    sec = await secure_sandbox(adapter, SecureConfig(install_strategy="running"))

    yield sec  # type: ignore[misc]

    # Don't call sec.stop() — this is a shared sandbox, not one we created.
    # blaxel adapter.stop() calls sandbox.delete() which would destroy it.


# ─── Smoke tests ──────────────────────────────────────────


class TestBlaxelSmoke:
    async def test_provisions_session_id(self, secured: SecuredSandbox) -> None:
        assert secured.session_id
        assert isinstance(secured.session_id, str)

    async def test_reports_valid_security_mode(self, secured: SecuredSandbox) -> None:
        assert secured.security_mode in ("full", "landlock", "landlock-only", "minimal")

    async def test_exec_simple_command(self, secured: SecuredSandbox) -> None:
        result = await secured.exec("echo hello")
        assert result.exit_code == 0
        assert result.stdout.strip() == "hello"

    async def test_write_read_roundtrip(self, secured: SecuredSandbox) -> None:
        path = "/workspace/e2e-test-file.txt"
        content = f"e2e-roundtrip-{int(time.time() * 1000)}"

        write_result = await secured.write_file(path, content)
        assert write_result.success is True

        read_result = await secured.read_file(path)
        assert read_result.success is True
        if read_result.success:
            assert read_result.content.strip() == content


# ─── Policy enforcement ───────────────────────────────────


class TestBlaxelPolicy:
    async def test_denies_env_write(self, secured: SecuredSandbox) -> None:
        # In passthrough mode (running strategy), file policy is enforced by FUSE.
        # The default policy on the pre-provisioned sandbox may not block .env writes.
        if secured.security_mode in ("full", "landlock"):
            result = await secured.write_file("/workspace/.env", "SECRET=leaked")
            # In passthrough mode, .env blocking depends on the server's policy config.
            # We only assert denial when NOT in passthrough (agentsh exec enforces).
            if not result.success:
                assert result.success is False

    async def test_allows_workspace_write(self, secured: SecuredSandbox) -> None:
        result = await secured.write_file("/workspace/allowed-file.txt", "allowed")
        assert result.success is True

    async def test_blocks_sudo(self, secured: SecuredSandbox) -> None:
        if secured.security_mode in ("full", "landlock"):
            result = await secured.exec("sudo whoami")
            assert result.exit_code != 0
