"""Tests for MCP server initialization."""

import os
from unittest.mock import patch

import pytest


class TestServer:
    """Tests for server initialization."""

    def test_server_import(self):
        """Test that server module can be imported."""
        from crustdata_mcp.server import mcp

        assert mcp is not None
        assert mcp.name == "Crustdata MCP Server"

    def test_main_function_exists(self):
        """Test that main function exists."""
        from crustdata_mcp.server import main

        assert callable(main)

    def test_main_http_function_exists(self):
        """Test that main_http function exists for HTTP transport."""
        from crustdata_mcp.server import main_http

        assert callable(main_http)

    def test_app_context_dataclass(self):
        """Test AppContext dataclass with client_factory."""
        from crustdata_mcp.client_factory import ClientFactory
        from crustdata_mcp.server import AppContext

        factory = ClientFactory()
        ctx = AppContext(client_factory=factory)
        assert ctx.client_factory is factory

    @pytest.mark.asyncio
    async def test_app_lifespan_requires_token(self):
        """Test that lifespan raises error without token."""
        from crustdata_mcp.server import app_lifespan, mcp

        with patch.dict(os.environ, {}, clear=True):
            os.environ.pop("CRUSTDATA_TOKEN", None)
            with pytest.raises(ValueError, match="CRUSTDATA_TOKEN"):
                async with app_lifespan(mcp):
                    pass

    @pytest.mark.asyncio
    async def test_app_lifespan_with_token(self):
        """Test that lifespan works with CRUSTDATA_TOKEN."""
        from crustdata_mcp.server import app_lifespan, mcp

        with patch.dict(os.environ, {"CRUSTDATA_TOKEN": "test-token"}, clear=True):
            async with app_lifespan(mcp) as ctx:
                assert ctx.client is not None
                assert ctx.client.api_token == "test-token"

    @pytest.mark.asyncio
    async def test_app_lifespan_http_does_not_require_token(self):
        """Test that HTTP lifespan works without token (per-request auth)."""
        from crustdata_mcp.server import app_lifespan_http, mcp

        with patch.dict(os.environ, {}, clear=True):
            os.environ.pop("CRUSTDATA_TOKEN", None)
            async with app_lifespan_http(mcp) as ctx:
                # Should have a client_factory, but no pre-created client
                assert ctx.client_factory is not None

    def test_main_http_uses_passthrough_verifier(self):
        """Test that main_http uses PassthroughTokenVerifier for per-request auth."""
        from crustdata_mcp.auth import PassthroughTokenVerifier
        from crustdata_mcp.server import main_http

        # Verify the import is used in main_http
        # We can't easily run main_http without it actually starting the server,
        # but we can verify the import path exists
        assert PassthroughTokenVerifier is not None
