"""REST API layer for universal LLM integration."""

from starlette.routing import Route
from starlette.responses import JSONResponse
from starlette.requests import Request


def create_rest_routes(mcp_server):
    """Create REST API routes that reuse the existing ToolRegistry."""

    async def list_tools(request: Request):
        """GET /api/tools - List all available tools."""
        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):
        """POST /api/tools/{name} - Execute a tool."""
        tool_name = request.path_params["name"]
        body = await request.json()

        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):
        """GET /openapi.json - OpenAPI specification."""
        paths = {}

        for name, config in mcp_server.registry._tools.items():
            schema = {}
            if config["schema"]:
                schema = config["schema"].model_json_schema()

            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"},
                                        },
                                    }
                                }
                            },
                        }
                    },
                }
            }

        spec = {
            "openapi": "3.0.0",
            "info": {
                "title": "Pier Cloud MCP Server",
                "version": mcp_server.version,
                "description": "Universal tool server for any LLM",
            },
            "servers": [{"url": "https://mcp.piercloud.io"}],
            "paths": {
                "/api/tools": {
                    "get": {
                        "summary": "List all tools",
                        "responses": {
                            "200": {
                                "description": "List of tools",
                                "content": {
                                    "application/json": {
                                        "schema": {
                                            "type": "object",
                                            "properties": {
                                                "tools": {
                                                    "type": "array",
                                                    "items": {"type": "object"},
                                                }
                                            },
                                        }
                                    }
                                },
                            }
                        },
                    }
                },
                **paths,
            },
        }

        return JSONResponse(spec)

    return [
        Route("/api/tools", endpoint=list_tools),
        Route("/api/tools/{name}", endpoint=execute_tool, methods=["POST"]),
        Route("/openapi.json", endpoint=openapi_spec),
    ]
