"""SSE server for production deployment."""

from mcp.server.sse import SseServerTransport
from starlette.applications import Starlette
from starlette.routing import Route
from starlette.responses import Response
from pier_mcp.rest_api import create_rest_routes


def create_sse_server(mcp_server):
    """Create Starlette app with SSE transport and REST API."""
    
    sse = SseServerTransport("/mcp/sse")
    
    async def handle_sse(request):
        async with sse.connect_sse(
            request.scope,
            request.receive,
            request._send,
        ) as streams:
            await mcp_server.server.run(
                streams[0],
                streams[1],
                mcp_server.server.create_initialization_options(),
            )
        return Response()
    
    async def handle_messages(request):
        await sse.handle_post_message(request.scope, request.receive, request._send)
        return Response()
    
    # Combine MCP and REST routes
    routes = [
        Route("/mcp/sse", endpoint=handle_sse),
        Route("/mcp/messages", endpoint=handle_messages, methods=["POST"]),
        *create_rest_routes(mcp_server),
    ]
    
    app = Starlette(routes=routes)
    
    return app
