"""E2B end-to-end tests — mirrors e2b.e2e.test.ts."""

from __future__ import annotations

import time

import pytest
import pytest_asyncio

from tests.e2e.conftest import ENV, skip_no_e2b

from agentsh_secure_sandbox import SecuredSandbox, secure_sandbox
from agentsh_secure_sandbox.adapters import e2b

pytestmark = [pytest.mark.e2e, pytest.mark.timeout(300), skip_no_e2b, pytest.mark.asyncio(loop_scope="module")]

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


@pytest_asyncio.fixture(scope="module", loop_scope="module")
async def secured() -> SecuredSandbox:  # type: ignore[misc]
    from e2b import AsyncSandbox  # type: ignore[import-untyped]

    raw = await AsyncSandbox.create("agentsh-sandbox", api_key=ENV["E2B_API_KEY"], timeout=600)
    adapter = e2b(raw)
    sec = await secure_sandbox(adapter)

    yield sec  # type: ignore[misc]

    await sec.stop()


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


class TestE2BSmoke:
    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", "ptrace", "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 TestE2BPolicy:
    async def test_denies_env_write(self, secured: SecuredSandbox) -> None:
        result = await secured.write_file("/workspace/.env", "SECRET=leaked")
        # In full security mode, FUSE blocks .env writes.
        if secured.security_mode == "full":
            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:
        result = await secured.exec("sudo whoami")
        # E2B runs as root — sudo is a no-op and succeeds.
        # In full mode with seccomp, sudo may be blocked.
        if secured.security_mode == "full":
            assert result.exit_code != 0

    async def test_blocks_env_command(self, secured: SecuredSandbox) -> None:
        result = await secured.exec("env")
        # In full mode, agentsh blocks env enumeration.
        if secured.security_mode == "full":
            assert result.exit_code != 0

    async def test_blocks_printenv(self, secured: SecuredSandbox) -> None:
        result = await secured.exec("printenv")
        if secured.security_mode == "full":
            assert result.exit_code != 0

    async def test_allows_npm_registry(self, secured: SecuredSandbox) -> None:
        result = await secured.exec(
            'curl -s -o /dev/null -w "%{http_code}" https://registry.npmjs.org/'
            ' || echo "no-curl"'
        )
        if "no-curl" not in result.stdout:
            assert result.stdout.strip() == "200"

    async def test_blocks_unauthorized_network(self, secured: SecuredSandbox) -> None:
        result = await secured.exec(
            "curl -s -o /dev/null -w '%{http_code}' --connect-timeout 5"
            " https://evil.example.com 2>&1"
        )
        assert result.stdout.strip() != "200"

    async def test_filters_sensitive_env_vars(self, secured: SecuredSandbox) -> None:
        result = await secured.exec('bash -c "echo $SECRET_KEY"')
        assert result.stdout.strip() == ""
