from __future__ import annotations

from typing import TYPE_CHECKING

from fastmcp import FastMCP
from starlette.requests import Request
from starlette.responses import JSONResponse, Response

if TYPE_CHECKING:
    from relay.server.db import RelayDB
    from relay.server.state import RelayState


async def _authorize_api_key(
    request: Request, db: RelayDB
) -> tuple[str | None, list[str]]:
    api_key = request.headers.get("x-api-key", "")
    if not api_key:
        return None, []
    account = await db.get_account_by_api_key(api_key)
    if account is None:
        return None, []
    user_id = request.query_params.get("user_id", "")
    if not user_id:
        return None, []
    user = await db.get_user(user_id)
    if user is None or user.account_email != account.email:
        return None, []
    return user_id, await db.get_user_groups(user_id)


def register_api_routes(mcp: FastMCP, state: RelayState, db: RelayDB) -> None:
    @mcp.custom_route("/auth/groups/{group_id}/messages", methods=["GET"])
    async def get_messages(request: Request) -> Response:
        user_id, authorized = await _authorize_api_key(request, db)
        group_id = request.path_params["group_id"]
        if user_id is None or group_id not in authorized:
            return JSONResponse({"error": "unauthorized"}, status_code=401)

        since_seq = int(request.query_params.get("since_seq", "0"))
        limit = int(request.query_params.get("limit", "100"))

        rows = await db.get_messages_after(group_id, since_seq)
        messages = [
            {
                "message_id": row.message_id,
                "group_id": row.group_id,
                "from_peer": row.from_peer,
                "from_display": row.from_display,
                "content": row.content,
                "timestamp": row.timestamp.isoformat(),
                "seq": row.seq,
            }
            for row in rows[:limit]
        ]
        return JSONResponse({"messages": messages})

    @mcp.custom_route("/auth/groups/{group_id}/peers", methods=["GET"])
    async def get_peers(request: Request) -> Response:
        user_id, authorized = await _authorize_api_key(request, db)
        group_id = request.path_params["group_id"]
        if user_id is None or group_id not in authorized:
            return JSONResponse({"error": "unauthorized"}, status_code=401)

        peers = await state.list_peers(group_id)
        peer_list = [
            {
                "user_id": p.user_id,
                "display_name": p.display_name,
                "online": p.online,
            }
            for p in peers
        ]
        return JSONResponse({"peers": peer_list})
