"""Vercel end-to-end tests — mirrors vercel.e2e.test.ts."""

from __future__ import annotations

import time

import pytest

from tests.e2e.conftest import ENV, skip_no_vercel

from agentsh_secure_sandbox import SecuredSandbox, secure_sandbox
from agentsh_secure_sandbox.adapters import vercel
from agentsh_secure_sandbox.adapters.vercel import VercelSandbox

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

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


@pytest.fixture(scope="module")
async def secured() -> SecuredSandbox:  # type: ignore[misc]
    sb = await VercelSandbox.create(
        token=ENV["VERCEL_TOKEN"],
        project_id=ENV["VERCEL_PROJECT_ID"],
        team_id=ENV["VERCEL_TEAM_ID"],
    )

    # Install system dependencies required by agentsh
    await sb.run_command("dnf", ["install", "-y", "libseccomp", "fuse3", "fuse3-libs"], sudo=True)

    adapter = vercel(sb)
    sec = await secure_sandbox(adapter)

    yield sec  # type: ignore[misc]

    await sec.stop()


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


class TestVercelSmoke:
    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 TestVercelPolicy:
    async def test_denies_env_write(self, secured: SecuredSandbox) -> None:
        # File deny rules require FUSE or landlock for enforcement
        if secured.security_mode in ("full", "landlock"):
            result = await secured.write_file("/workspace/.env", "SECRET=leaked")
            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:
        # Command interception for sub-processes requires seccomp user_notify
        if secured.security_mode in ("full", "landlock"):
            result = await secured.exec("sudo whoami")
            assert result.exit_code != 0

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

    async def test_blocks_printenv(self, secured: SecuredSandbox) -> None:
        if secured.security_mode in ("full", "landlock"):
            result = await secured.exec("printenv")
            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() == ""
