"""REST/WebSocket API gateway — local access to the node."""
from __future__ import annotations

import logging
from typing import Any

from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from pydantic import BaseModel

log = logging.getLogger(__name__)


class ChatRequest(BaseModel):
    message: str
    max_tokens: int = 1024
    temperature: float = 0.7


class ChatResponse(BaseModel):
    response: str
    cached: bool = False


def create_app(node: Any) -> FastAPI:
    """Create the FastAPI application for the node."""
    app = FastAPI(title=f"HiveMind Node: {node.name}", version="1.2.2")

    @app.get("/status")
    async def status():
        return node.status

    @app.post("/chat", response_model=ChatResponse)
    async def chat(req: ChatRequest):
        # Check cache first to report cache status
        cached = node.cache.lookup(req.message)
        if cached:
            return ChatResponse(response=cached, cached=True)

        response = await node.chat(req.message)
        return ChatResponse(response=response, cached=False)

    @app.get("/plugins")
    async def plugins():
        return {
            "loaded": node.plugins.loaded,
            "capabilities": [
                {"plugin": c.plugin, "name": c.name, "description": c.description}
                for c in node.plugins.all_capabilities()
            ],
        }

    @app.websocket("/ws")
    async def websocket_chat(ws: WebSocket):
        """WebSocket endpoint for streaming chat."""
        await ws.accept()
        log.info("WebSocket client connected")
        try:
            while True:
                message = await ws.receive_text()
                response = await node.chat(message)
                await ws.send_text(response)
        except WebSocketDisconnect:
            log.info("WebSocket client disconnected")

    return app
