"""Tests for Grasp SDK initialization and error handling."""

import os
import pytest
from grasp import Grasp, AsyncGrasp
from grasp._exceptions import AuthenticationError


class TestGraspInitialization:
    """Test Grasp client initialization."""

    def test_create_client_with_explicit_params(self):
        """Test creating client with explicit api_key and base_url."""
        client = Grasp(
            api_key="test-key",
            base_url="http://localhost:3000",
        )
        assert client is not None
        assert isinstance(client, Grasp)

    def test_create_client_with_env_variables(self):
        """Test creating client using environment variables."""
        client = Grasp()
        assert client is not None
        assert isinstance(client, Grasp)


class TestGraspErrorHandling:
    """Test Grasp error handling."""

    def setup_method(self, method):
        """Setup before each test method."""
        self.grasp = Grasp(
            api_key=os.environ["GRASP_API_KEY"],
            base_url=os.environ["GRASP_BASE_URL"],
        )

    def test_error_no_api_key(self):
        """Test error when no API key is provided."""
        original_key = os.environ.pop("GRASP_API_KEY", None)

        try:
            with pytest.raises(AuthenticationError, match="Missing API key"):
                Grasp()
        finally:
            if original_key:
                os.environ["GRASP_API_KEY"] = original_key

    def test_error_invalid_container_id(self):
        """Test error when connecting to invalid container ID."""
        with pytest.raises(Exception):
            self.grasp.connect("invalid-container-id")

    def test_error_shutdown_invalid_container(self):
        """Test error when shutting down container with invalid ID."""
        temp_container = self.grasp.create()
        original_id = temp_container._id

        try:
            temp_container._id = "invalid-id"
            with pytest.raises(Exception):
                temp_container.shutdown()
        finally:
            temp_container._id = original_id
            try:
                temp_container.shutdown()
            except Exception:
                pass


@pytest.mark.asyncio
class TestAsyncGraspInitialization:
    """Test AsyncGrasp client initialization."""

    async def test_create_client_with_explicit_params(self):
        """Test creating async client with explicit api_key and base_url."""
        client = AsyncGrasp(
            api_key="test-key",
            base_url="http://localhost:3000",
        )
        assert client is not None
        assert isinstance(client, AsyncGrasp)
        await client.close()

    async def test_create_client_with_env_variables(self):
        """Test creating async client using environment variables."""
        client = AsyncGrasp()
        assert client is not None
        assert isinstance(client, AsyncGrasp)
        await client.close()


@pytest.mark.asyncio
class TestAsyncGraspErrorHandling:
    """Test AsyncGrasp error handling."""

    def setup_method(self, method):
        """Setup before each test method."""
        self.grasp = AsyncGrasp(
            api_key=os.environ["GRASP_API_KEY"],
            base_url=os.environ["GRASP_BASE_URL"],
        )

    async def test_error_no_api_key(self):
        """Test error when no API key is provided."""
        original_key = os.environ.pop("GRASP_API_KEY", None)

        try:
            with pytest.raises(AuthenticationError, match="Missing API key"):
                AsyncGrasp()
        finally:
            if original_key:
                os.environ["GRASP_API_KEY"] = original_key

    async def test_error_invalid_container_id(self):
        """Test error when connecting to invalid container ID."""
        with pytest.raises(Exception):
            await self.grasp.connect("invalid-container-id")

    async def test_error_shutdown_invalid_container(self):
        """Test error when shutting down container with invalid ID."""
        temp_container = await self.grasp.create()
        original_id = temp_container._id

        try:
            temp_container._id = "invalid-id"
            with pytest.raises(Exception):
                await temp_container.shutdown()
        finally:
            temp_container._id = original_id
            try:
                await temp_container.shutdown()
            except Exception:
                pass
