from __future__ import annotations

from typing import Annotated

from mcp.server.fastmcp import FastMCP
from mcp.types import TextContent, ToolAnnotations
from pydantic import Field

from .. import routes
from ..client import ApiClient
from ..decorators import handle_api_errors


def register(
    mcp: FastMCP,
    client: ApiClient,
    *,
    write_hint: ToolAnnotations,
    track,
) -> None:
    @mcp.tool(annotations=write_hint.model_copy(update={"title": "Capture Feedback"}))
    @handle_api_errors
    @track
    async def capture_feedback(
        session_token: Annotated[str, Field(description="Session token from a previous call.")],
        rating: Annotated[int, Field(description="Quality rating from the user (1-10).", ge=1, le=10)],
        question_summary: Annotated[str, Field(description="Brief summary of the user's question.")],
        feedback: Annotated[
            str,
            Field(
                description="Your assessment of how well the knowledge served the user — what worked, what was missing, any gaps you noticed.",
                default="",
            ),
        ] = "",
    ) -> list[TextContent]:
        """Submit feedback on how well you answered given the available knowledge.

        When to call: After the conversation wraps up, ask the user if they need anything
        else. If not, ask them to rate how well you answered from 1-10, then call this tool
        with their rating and your own assessment. The user only gives a number.
        """
        body: dict = {
            "session_token": session_token,
            "rating": rating,
            "question_summary": question_summary,
        }
        if feedback:
            body["feedback"] = feedback

        data = await client.post(f"{routes.expert_feedback()}?source=mcp", body)
        message = data.get("message", "Feedback recorded.")
        return [TextContent(type="text", text=message)]
