"""Daytona end-to-end tests — mirrors daytona.e2e.test.ts."""

from __future__ import annotations

import time

import pytest

from tests.e2e.conftest import skip_no_daytona

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

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

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


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

    client = Daytona()
    raw = await client.create()
    adapter = daytona(raw)
    sec = await secure_sandbox(adapter)

    yield sec  # type: ignore[misc]

    # Teardown: delete the sandbox via the Daytona client
    if raw and client:
        await client.delete(raw)


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


class TestDaytonaSmoke:
    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 TestDaytonaPolicy:
    async def test_denies_env_write(self, secured: SecuredSandbox) -> None:
        result = await secured.write_file("/workspace/.env", "SECRET=leaked")
        if secured.security_mode in ("full",):
            assert result.success is False
        elif result.success:
            pytest.skip("FUSE not active — .env deny not enforced in this mode")

    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")
        assert result.exit_code != 0

    async def test_blocks_env_command(self, secured: SecuredSandbox) -> None:
        result = await secured.exec("env")
        if secured.security_mode in ("full", "landlock"):
            assert result.exit_code != 0
        elif result.exit_code == 0:
            pytest.skip("env command not blocked in this security mode")

    async def test_blocks_printenv(self, secured: SecuredSandbox) -> None:
        result = await secured.exec("printenv")
        if secured.security_mode in ("full", "landlock"):
            assert result.exit_code != 0
        elif result.exit_code == 0:
            pytest.skip("printenv command not blocked in this security mode")

    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() == ""
