"""HTTP server with SSE (MCP) and REST API (ChatGPT) support."""

from mcp.server.sse import SseServerTransport
from starlette.applications import Starlette
from starlette.routing import Route
from starlette.responses import Response, JSONResponse
from starlette.requests import Request


def create_http_server(mcp_server):
    """Create Starlette app with SSE and REST routes."""

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

    async def list_tools(request: Request):
        tools = []
        for name, config in mcp_server.registry._tools.items():
            tool_def = {"name": name, "description": config["description"]}
            if config["schema"]:
                tool_def["parameters"] = config["schema"].model_json_schema()
            tools.append(tool_def)
        return JSONResponse({"tools": tools})

    async def execute_tool(request: Request):
        tool_name = request.path_params["name"]
        body = await request.json()

        body["_client_id"] = request.headers.get("X-Client-ID")
        body["_client_secret"] = request.headers.get("X-Client-Secret")

        try:
            result = await mcp_server.registry.execute(tool_name, body)
            return JSONResponse({"success": True, "result": result[0].text})
        except Exception as e:
            return JSONResponse({"success": False, "error": str(e)}, status_code=400)

    async def openapi_spec(request: Request):
        paths = {}
        for name, config in mcp_server.registry._tools.items():
            schema = config["schema"].model_json_schema() if config["schema"] else {}
            paths[f"/api/tools/{name}"] = {
                "post": {
                    "summary": config["description"],
                    "requestBody": {
                        "content": {"application/json": {"schema": schema}}
                    },
                    "responses": {
                        "200": {
                            "description": "Success",
                            "content": {
                                "application/json": {
                                    "schema": {
                                        "type": "object",
                                        "properties": {
                                            "success": {"type": "boolean"},
                                            "result": {"type": "string"},
                                        },
                                    }
                                }
                            },
                        }
                    },
                }
            }

        return JSONResponse(
            {
                "openapi": "3.0.0",
                "info": {
                    "title": "Pier Cloud MCP Server",
                    "version": mcp_server.version,
                    "description": "Universal tool server for any LLM",
                },
                "servers": [{"url": "https://piercloud.io/mcp"}],
                "paths": {
                    "/api/tools": {
                        "get": {
                            "summary": "List all tools",
                            "responses": {"200": {"description": "List of tools"}},
                        }
                    },
                    **paths,
                },
            }
        )

    return Starlette(
        routes=[
            Route("/mcp/sse", endpoint=handle_sse),
            Route("/mcp/messages", endpoint=handle_messages, methods=["POST"]),
            Route("/api/tools", endpoint=list_tools),
            Route("/api/tools/{name}", endpoint=execute_tool, methods=["POST"]),
            Route("/openapi.json", endpoint=openapi_spec),
        ]
    )
